Reputation: 5068
I'm populating a combobox from a datasource and I have code for when the user changes the selection in the combobox. So obviously I don't want the code in the SelectedIndexChanged method to fire on form load.
This SO question was answered by suggesting two things:
1) Before and after loading the data to the combobox use this code:
private void LoadYourComboBox()
{
this.comboBox1.SelectedIndexChanged -= new EventHandler(comboBox1_SelectedIndexChanged);
// Set your bindings here . . .
this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
}
I tried that with this code:
this.cboSelectCategory.SelectedIndexChanged -= new EventHandler(cboSelectCategory_SelectedIndexChanged);
However, the cboSelectCategory_SelectedIndexChanged
part has a red error squiggly and hovering over it says: The name cboSelectCategory_SelectedIndexChanged does not exist in the current context
. I tried that code in both the form_load and the method that actually populates the combobox.
2) That same SO question had the answer to use the event SelectedIndexChangeCommitted
.
private void cboSelectCompany_SelectedIndexChangeCommitted(object sender, EventArgs e)
{
string selectedCat = cboSelectCategory.SelectedValue.ToString();
Console.WriteLine(selectedCat);
}
But that event isn't firing when I change the selection in the combobox.
Am I missing something somewhere? Is my code off or in the wrong place?
Upvotes: 0
Views: 87
Reputation: 74730
So obviously I don't want the code in the SelectedIndexChanged method to fire on form load.
If you bind your combobox in the form's constructor (after InitializeComponent()
) then SelectedIndexChanged
will fire before the form is visible, so you can simply return from the selectedindexchanged event if the form is invisible:
public MainForm()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Code");
dt.Rows.Add("Milk", "MLK");
dt.Rows.Add("Bread", "BRD_WHITE");
dt.Rows.Add("Bread", "BRD_BROWN");
dt.Rows.Add("Coffee", "COFF");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Code";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.Visible)
return;
MessageBox.Show("a");
}
It's often easier to simply return from an event handler at an unwanted time than to mess around trying to remove and add event handlers
Side note: If you use a strongly typed dataset and create the bindings using the windows forms designer, the event doesn't fire, I believe because the forms designer InitializeComponent()
calls Begin/EndInit on the components at the start and end
Upvotes: 1