请教个问题,我开发的查看数据库行数的窗体小软件,点击连接数据库,若点击多遍,其下拉列表,所连接的数据库就会重复出现很多次,若切换成其他数据库,新老数据库都会出现在下拉列表里,具体现象如图片;
怎么处理一下,让数据库只显示当前需要的呢,而不要多次点击后,重复出现,或在新查询里面,也显示在此之前查询的数据库,新、老掺杂在一起;
“连接数据库”按钮的点击代码如下,请大家帮我看看怎么完善一下呢,谢谢;
private void button5_Click(object sender, EventArgs e)
{
String connectionString = String.Format("server={0};uid={1};pwd={2};", textBoxHost.Text, textBoxUser.Text, textBoxPassword.Text);
string query = "SELECT name from sys.databases where name NOT IN ('master', 'tempdb', 'model', 'msdb')";
SqlConnection sqlconn = new SqlConnection(connectionString);
sqlconn.Open();
//SqlString = "select name from master..sysdatabases";
//加载数据并显示
try
{
MessageBox.Show("数据库连接成功!");
//查询条件和SqlConnection连接
//SqlCommand cmd = new SqlCommand(SqlString, sqlconn);
//数据适配器
//SqlDataAdapter sda = new SqlDataAdapter();
//sda.SelectCommand = cmd;
//DataTable存储数据
//DataTable dt = new DataTable();
//sda.Fill(dt);
//dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("数据库连接失败,请填写准确连接参数");
return;
}
finally
{
conn.Close();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string dbName = reader.GetString(0);
comboBox1.Items.Add(dbName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}