Čeněk Sůva
Čeněk Sůva

Reputation: 53

Disable event firing itself from its code

SelectedIndexChange event is causing my trouble here as I change index in this event and I would like to avoid it.

I still need to call the event when I change index manually but not in code. Because as you may notice when I change index inside the event it fires itself again.

Upvotes: 3

Views: 1303

Answers (2)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

Use a boolean to specify that you are inside event.

private bool _isRunning = false;
private void SelectedIndexChange(...)
{
    if(_isRunning) return;
    _isRunning = true;

    // do your things

    _isRunning = false;
}

Edit. As noted by Scott Chamberlain if there is potential of happening error inside event then use finally statement to always reset flag.

private bool _isRunning = false;
private void SelectedIndexChange(...)
{
    if(_isRunning) return;
    _isRunning = true;
    try
    {
        // do your things
    }
    finally
    { 
        _isRunning = false;
    }
}

Upvotes: 5

Reza Aghaei
Reza Aghaei

Reputation: 125197

As mentioned by Ron in comments you can remove the handler from event and do your job and then assign handler to event again:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Remove handler
    this.comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;

    //Change index here

    //Assign handler again
    this.comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}

Also the other way that Ron has suggested is implemented by M.Kazem and you can use that option as well.

Upvotes: 3

Related Questions