Reputation: 141
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
Reputation: 5403
comboBoxSelectDatabase.Items.Add(command);
is wrong, it should be:
while (reader.Read())
{
comboBoxSelectDatabase.Items.Add(reader["name"].ToString());
}
Upvotes: 1
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