简体   繁体   中英

How to prevent event firing after programmatically interacting with controls?

I have a CheckedBoxList. Also I have a ItemCheck event attached to it, so a fuction is executed after I checked an item. But the problem is, at one point in my program I need to programmatically check/uncheck items. And this action triggers the event function.

My guess is is also applies to other controls.

How can I prevent such behaviour? I need function to be run only when user interacts with it, not when I am doing something with control inside my app.

Use a flag

private bool _updating;

void CheckedBoxList_ItemCheck(sender object, EventArgs e)
{
    if (_updating)  return;

    // Execute item check code
}

void SomewhereElse()
{
    _updating = true;
    try {
        // programmatically check/uncheck items
    } finally {
        _updating = false;
    }
}

The try/finally statement ensures that the flag gets unset even if an exception should occur or if the try code block is left with return (or break within a loop).

You can wrap all your changes to CheckedBoxList in a function and use that function everytime. The code may look something like this:

private void UpdateCheckedListBox() // You would need to add your parameters
{
    checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
    // your changes to checked list box goes here
    checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}

First create boolean variable at form level:

bool dontUpdate = false;

Then in your Checklist Itemcheck method, execute only if dontUpdate is false:

public void CheckedBoxList_ItemCheck(sender object, EventArgs e) {
    if (dontUpdate) return;
    //else execute
}

Now when checking items programmatically, set it to true:

void nativeUpdate(){
    dontUpdate = true;
    //Do your items check
    dontUpdate = false;
}

Whenever you need to check item/S programmatically, use nativeUpdate method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM