我有一个带有许多控件的 Windows 窗体。其中一小部分是登录到 SQL 服务器并获取数据库名称列表并将集合分配给组合框。
private void InitializeComponent()
{
//...
//...
this.ServerTB = new System.Windows.Forms.TextBox();
this.UserNameTB = new System.Windows.Forms.TextBox();
this.PasswordTB = new System.Windows.Forms.TextBox();
//...
//...
this.ServerTB.TextChanged += new System.EventHandler(this.OnSQLServerChanged);
this.UserNameTB.TextChanged += new System.EventHandler(this.OnSQLServerChanged);
this.PasswordTB.TextChanged += new System.EventHandler(this.OnSQLServerChanged);
this.DatabaseCmbBox = new System.Windows.Forms.ComboBox();
//...
//...
this.DatabaseCmbBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.DatabaseCmbBox_Click);
//....
}
private void DatabaseCmbBox_Click(object sender, MouseEventArgs e)
{
MessageBox.Show(sender.GetType().ToString());
this.Cursor = Cursors.IBeam;
List<string> dbList = new List<string>();
dbList = GetDatabaseList();
DatabaseCmbBox.DataSource = dbList;
DatabaseCmbBox.SelectedIndex = -1;
if (dbList.Count > 0)
{
DatabaseCmbBox.MouseClick -= DatabaseCmbBox_Click;
}
DatabaseCmbBox.Focus();
this.Cursor = Cursors.Default;
}
protected List<string> GetDatabaseList()
{
List<string> list = new List<string>();
string conString = "server=" + ServerTB.Text + ";uid=" + UserNameTB.Text + ";pwd=" + PasswordTB.Text + "; database=master";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("select name from sys.databases where name not in ('master', 'model', 'tempdb', 'msdb') ", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
dr.Close();
}
cmd.Dispose();
}
con.Close();
}
}
catch(SqlException ex)
{
DatabaseCmbBox.MouseClick -= DatabaseCmbBox_Click;
MessageBox.Show(ex.Message);
ServerTB.Focus();
}
return list;
}
private void OnSQLServerChanged(object sender, EventArgs e)
{
DatabaseCmbBox.MouseClick += DatabaseCmbBox_Click;
}
我在获取数据库列表时没有问题。这样做大约需要 10 秒钟。通过事件处理程序中的消息框,我发现 MouseClick 事件无缘无故地被触发了 38 次。即使我使用 Enter 事件或 Click 事件而不是 MouseClick 事件,也会发生同样的事情。
为什么会发生这种情况,以及如何使用这些事件?
在此先感谢,RPS。