My C# application has a comboBox
with a SelectedIndexChanged
event. Usually, I want this event to fire, but but sometimes I need the event to not fire. My comboBox
is an MRU file list. If a file in the list is found to not exist, the item is removed from the comboBox
, and the comboBox
SelectedIndex
is set to zero. However, setting the comboBox
SelectedIndex
to zero causes the SelectedIndexChanged
event to fire, which in this case is problematic because it causes some UIF code to be run in the event handler. Is there a graceful way to disable/enable events for C# form controls? Thanks.
I'm surprised there isn't a better way of doing this, but this is the way I do it. I actually use the Tag
field of most controls so I don't have to subclass the control. And I use true
/null
as the values, since null
is the default.
Of course, if you are actually using Tag
, you'll need to do it differently...
In handler:
private void control_Event(object sender, EventArgs e)
{
if (control.Tag != null ) return;
// process the events code
...
}
In main code
try
{
control.Tag = true;
// set the control property
control.Value = xxx;
or
control.Index = xxx;
or
control.Checked = xxx;
...
}
finally
{
control.Tag = null;
}
I have encountered this many times over the years. My solution is to have a class level variable called _noise and if I know I am about to change the index of combo or any other similiar control that fires when the selected index changes, I do the following in code.
private bool _noise;
Here is the code for the control event handler
private void cbTest_SelectedIndexChange(object sender, EventArgs e)
{
if (_noise) return;
// process the events code
...
}
Then when I know I am going to change the index, I do the following:
_noise = true; // cause the handler to ignore the noise...
cbTest.Index = value;
_noise = false; // let the event process again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With