[英]C# windows forms listbox selected index changed event fires on form load and button click
I'm coding a program that allows a user to search for a customers order using the customers name the user types in a name in a TextBox
and the search results are displayed in a ListBox
control the user than has to select a name from the list box and customer's orders are displayed in a DataGridView
the problem is once the customer clicks the search button the SelectedIndex
changed event fires and causes the program to crash. 我正在编写一个程序,允许用户使用客户名称搜索客户订单,用户在
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();
}
I really don't understand why the SelctedIndexChanged
event fires when I click the search button is there something that I am missing maybe? 我真的不明白为什么当我点击搜索按钮时会引发
SelctedIndexChanged
事件是否有我可能遗漏的东西?
Since you set the datasource of lstResults
it will call SelectedIndexChanged
, you can do as below 由于您设置了
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.