0

I have two comboboxes, comboBoxSelectServer and comboBoxSelectDatabase.

Based on the value selected in comboBoxSelectServer when the user clicks on comboBoxSelectDatabase they will get the various databases from that server.

However, when running the application I'm not getting any databases returned in comboBoxSelectDatabase.

I think its due to the below section of my code, as on debugging its not pulling back anything.

comboBoxSelectDatabase.Items.Add(command);

I've included my code below;

if (comboBoxSelectServer.SelectedIndex == 0)
{
    string commandTextSERV1 = "SELECT name FROM master.sys.databases " +
                              "where name LIKE 'Client_%'";

    string connectionString = Properties.Settings.Default.connectionStringSERV1;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandTextSERV1, con);

        try
        {
            con.Open();
            command.ExecuteNonQuery();
            SqlDataReader reader = command.ExecuteReader();

            if (reader.Read())
            {
                comboBoxSelectDatabase.Items.Add(command);
            }
            else
            {
                MessageBox.Show("Error");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
}
3
  • 2
    I think your problem is related to comboBoxSelectDatabase.Items.Add(command);. Here you are adding the SqlCommand object and not any of the returned DataRows to the drop down Commented May 1, 2018 at 10:26
  • @JayV Yes I've thought the same..but I don't know what to replace it with to pull back the database list. I've tried a few options but nothing works so far.. Commented May 1, 2018 at 10:28
  • Take a google of executereader it comes with examples Commented May 1, 2018 at 10:28

2 Answers 2

1
comboBoxSelectDatabase.Items.Add(command);

is wrong, it should be:

while (reader.Read())
{
    comboBoxSelectDatabase.Items.Add(reader["name"].ToString());
}
Sign up to request clarification or add additional context in comments.

Comments

0

Issue is with your following statement. here you are adding command object, instead of reader rows.

comboBoxSelectDatabase.Items.Add(command);

Change it to

while (reader.Read())
{
    comboBoxSelectDatabase.Items.Add(Convert.ToString(reader["name"]));
}

This should populate the combox with database name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.