Reputation: 5044
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:
Can anyone please help me to populate subcategories based on selection from first combobox.
Upvotes: 0
Views: 1449
Reputation: 10704
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
Upvotes: 2