Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying ComboBox SelectedIndex Without Triggering Event in C#

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.

like image 995
Jim Fell Avatar asked Jul 28 '10 19:07

Jim Fell


2 Answers

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;
 }
like image 148
Mark Lakata Avatar answered Nov 12 '22 17:11

Mark Lakata


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
like image 39
Les Smith Avatar answered Nov 12 '22 17:11

Les Smith