Reputation: 4292
I have a ComboBox
and in the form's load event it's populated with data. Now when I select an Item form the ComboBox
, it should perform some actions. So I know few events which can be used in this case like
SelectedIndexChanged
SelectedValueChanged
etc.
But the problem is those events are raised even when setting the DataSource
of the ComboBox and selecting a default index etc. when the form is loaded.
ComboBox1.DataSource = dt;
ComboBox1.SelectedIndex = -1;
What am I trying to do is that I just want to execute an action only when I select an item form the combo box. Is there a mouse event that could be used in this case?
Upvotes: 2
Views: 2553
Reputation: 989
The comboBox.SelectionChangeCommitted
Event seems to do that.
Otherwise you could set a boolean value before you bind the datasource which you can use inside the event to ignore it.
private bool blnIgnoreEvent = false;
// in Form_load
blnIgnoreEvent = true;
ComboBox1.DataSource = dt;
blnIgnoreEvent = false;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!blnIgnoreEvent)
{
// go ahead
}
}
Upvotes: 3
Reputation: 751
I don't believe there is another event that better handles what you'd like to do. XIVSolutions has a neat work-around for the event firing when you bind the data source: How to prevent selectedindexchanged event when DataSource is bound?
Also, since SelectedIndexChanged
works for all cases, why not just handle the first?
if (ComboBox1.SelectedIndex == -1)
{
return;
}
If -1 corresponds to a value you'd like to be able to select, just use a private field to store some bool
that you check to determine whether or not it is the first time the action has been executed.
Upvotes: 1