WHoward
WHoward

Reputation: 141

C# Return List of Databases in Combobox

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();
        }
    }
}

Upvotes: 0

Views: 504

Answers (2)

Richard Hansell
Richard Hansell

Reputation: 5403

comboBoxSelectDatabase.Items.Add(command);

is wrong, it should be:

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

Upvotes: 1

user1672994
user1672994

Reputation: 10849

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.

Upvotes: 0

Related Questions