C#窗体列表框选定的索引已更改事件在加载窗体并单击按钮时触发
本文关键字:窗体 加载 单击 事件 按钮 列表 索引 | 更新日期: 2023-09-27 18:21:54
我正在编写一个程序,允许用户使用用户在TextBox
中键入的客户名称搜索客户订单,搜索结果显示在ListBox
控件中用户不必从列表框中选择名称,客户订单显示在DataGridView
中问题是,一旦客户单击搜索按钮,SelectedIndex
更改事件引发并导致程序崩溃。
private void btnSearch_Click(object sender, EventArgs e)
{
string Query = "SELECT CustomerID, CompanyName FROM Customers WHERE (CompanyName ”+ “LIKE'%"+ txtSearch.Text + "%')";
clsDataTools.cmdComand = clsDataTools.con.CreateCommand();
clsDataTools.cmdComand.CommandText = Query;
clsDataTools.dtaDataAdapter = new SqlDataAdapter();
clsDataTools.dtaDataAdapter.SelectCommand = clsDataTools.cmdComand;
dsOrdersByCusName = new DataSet();
clsDataTools.con.Close();
clsDataTools.con.Open();
clsDataTools.dtaDataAdapter.Fill(dsOrdersByCusName);
clsDataTools.con.Close();
dsOrdersByCusName.Tables[0].TableName = "OrderBCusName";
lstResults.DataSource = dsOrdersByCusName.Tables[0];
lstResults.DisplayMember = "CompanyName";
lstResults.ValueMember = "CustomerID";
}
private void lstResults_SelectedIndexChanged(object sender, EventArgs d)
{
string Query = "SELECT * From Orders WHERE CustometID = '"
+ lstResults.SelectedValue
+ "'";
dataGridDataSet = new DataSet();
clsDataTools.dtaDataAdapter = new SqlDataAdapter();
clsDataTools.cmdComand = clsDataTools.con.CreateCommand();
clsDataTools.cmdComand.CommandText = Query;
clsDataTools.con.Close();
clsDataTools.con.Open();
clsDataTools.dtaDataAdapter.SelectCommand = clsDataTools.cmdComand;
clsDataTools.dtaDataAdapter.Fill(dataGridDataSet);
clsDataTools.con.Close();
dataGridDataSet.Tables[0].TableName = "Orders";
dgvCusOrders.DataSource = dataGridDataSet;
dgvCusOrders.DataMember = dataGridDataSet.Tables["Orders"].ToString();
}
我真的不明白为什么当我点击搜索按钮时SelctedIndexChanged
事件会触发——也许我遗漏了什么?
由于设置了lstResults
的数据源,它将调用SelectedIndexChanged
,因此可以执行以下
private void btnSearch_Click(object sender, EventArgs e)
{
//Remove the handler
this.lstResults.SelectedIndexChanged -= lstResults_SelectedIndexChanged;
//
// Your code
//
this.lstResults.SelectedIndexChanged += lstResults_SelectedIndexChanged; // Add the handler
}