Question

I have 2 ComboBox in one of my c# WinForms project, first contains the parent categories, and based on the category selected in first combobox i need to populate their child categories in second combobox.

Below is the code i am using to fill First comboBox.

private DataTable FillProductGroupID(int ParentID = -1)
        {
            DataTable dt = new DataTable();
            using (SqlConnection connection = new SqlConnection(@"server=***; uid=***; pwd=***; database=lowprice"))
            {
                try
                {
                    using (SqlCommand command = new SqlCommand("user_GetAllProductGroup", connection))
                    {
                        connection.Open();
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@ParentID", ParentID);
                        SqlDataAdapter adapter = new SqlDataAdapter(command);

                        adapter.Fill(dt);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    connection.Close();
                }
            }
            return dt;
        }

Here's my FormLoad event where the binding for the first combobox takes place.

 cbParentCategories.DataSource = FillProductGroupID();
            cbParentCategories.DisplayMember = "Name";
            cbParentCategories.ValueMember = "Id";

Here's my SelectedIndexChangedEvent of first combobox through which i am filling second combobox.

cbChildCategories.DataSource = 
FillProductGroupID(int.Parse(cbParentCategories.SelectedValue.ToString())); //Form Load Error Here.
            cbChildCategories.DisplayMember = "Name";
            cbChildCategories.ValueMember = "Id";

On the form load it just says, Input string was not in a correct format.

I have 2 questions:

  1. Why its checking for the selectedValue of SelectedIndexChangedEvent on FormLoad, it should be probably when i select first combobox.
  2. What could be the proper way to get the selectedvalue of the first combobox on selectedindexchanged event of first combobox.

Can anyone please help me to populate subcategories based on selection from first combobox.

Was it helpful?

Solution

Below line

 cbParentCategories.DataSource = FillProductGroupID();

Causes firing event of SelectedIndexChangedEvent.And selected item isnt valid to convert to int. So rather than using SelectedIndexChangedEvent. You can try using

SelectionChangeCommitted Event

This event is only called when user change the selected item in the combobox

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top