Kabza
Kabza

Reputation: 23

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.

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?

Upvotes: 2

Views: 3511

Answers (1)

Damith
Damith

Reputation: 63105

Since you set the datasource of lstResults it will call SelectedIndexChanged, you can do as below

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 
}

Upvotes: 3

Related Questions