Search code examples
c#listboxselectedindexchanged

Index change event C#


I was just wondering if there was anyway to execute the index change event for the first iteration.

My code looks like the following.

    private void cboxEvent_IndexChange(object sender, EventArgs e)
    {

        int value;

        value = cboxEvent.SelectedIndex;

        resetListBoxes(); 

        cboxEvent.SelectedIndex = value;

        csvExport(); 


    }

    private void cboxSLA_IndexChange(object sender, EventArgs e)
    {
        int value;

        value = cboxSLA.SelectedIndex;

        resetListBoxes(); 

        cboxNPA.SelectedIndex = value;

        csvExport(); 
    }
    private void cboxNPA_IndexChange(object sender, EventArgs e)
    {
        int value;

        value = cboxNPA.SelectedIndex;

        resetListBoxes(); 

        cboxNPA.SelectedIndex = value;

        csvExport(); 

    }

The problem is that once an index changes it resets the other listboxes and their Index change method is activated as well. Therefore it executes Their IndexChange method.

I would like for the code to be executed only once for the first Index Changed.

Any ideas?

Thanks in Advance

Chris


Solution

  • You can rewrite your IndexChanged handlers in this manner (same for all handlers):

    private bool _IgnoreIndexChange;
    
    private void cboxEvent_IndexChange(object sender, EventArgs e)
    {
        if (_IgnoreIndexChange)
            return;
    
        _IgnoreIndexChange = true;
        try
        {
            int value;
            value = cboxEvent.SelectedIndex;
            resetListBoxes(); 
            cboxEvent.SelectedIndex = value;
            csvExport(); 
        }
        finally
        {
            _IgnoreIndexChange = false;
        }    
    }
    

    So if any index will be changed by user - only IndexChanged handler of that combobox will run, no others.