Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancelling ListBox SelectedIndexChange Event

Is it possible to cancel the SelectedIndexChange event for a listbox on a winforms application? This seems like such a logical thing to have that I must be overlooking some easy feature. Basically, I have been popping up a message box asking if the user really wants to move to another item, as this will change the UI and I don't want their changes to be lost. I'd like to be able to cancel the event in case the user has not saved what they are working on. Is there a better way of doing this?

like image 472
Josh Avatar asked Mar 31 '10 20:03

Josh


3 Answers

You cannot cancel it.

What I did just a couple of days ago was to have a variable with the latest selected index. Then when the event fires, you ask the user if he wants to save, this is done in the eventhandler. If the user selected "Cancel" you change the id again.

The problem is that this will make the event fire once again. So what i've used is a bool just saying "Inhibit". And at the top of the eventhandler I have:

if(Inhibit)
   return;

Then below this where you ask the question you do something like this:

DialogResult result = MessageBox.Show("yadadadad", yadada cancel etc);
if(result == DialogResult.Cancel){
   Inhibit = true; //Make sure that the event does not fire again
   list.SelectedIndex = LastSelectedIndex; //your variable
   Inhibit = false; //Enable the event again
}
LastSelectedIndex = list.SelectedIndex; // Save latest index.
like image 178
Oskar Kjellin Avatar answered Oct 14 '22 12:10

Oskar Kjellin


This is exactly @Oskar Kjellin 's method, but with a twist. That is, one variable less and with a selected index changed event that really behaves like a selected index changed event. I often wonder why is selected index changed event getting fired even if I click on the exact same selected item. Here it doesn't. Yes it's a deviation, so be doubly sure if you want this to be there.

    int _selIndex = -1;
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex == _selIndex)
            return;

        if (MessageBox.Show("") == DialogResult.Cancel)
        {
            listBox1.SelectedIndex = _selIndex;
            return;
        }

        _selIndex = listBox1.SelectedIndex;
        // and the remaining part of the code, what needs to happen when selected index changed happens
    }
like image 11
nawfal Avatar answered Oct 14 '22 13:10

nawfal


I just ran into this exact problem. What I did is when the user makes changes, I set ListBox.Enabled = false; This disallows them to select a different index. Once they either save or discard their changes, I set ListBox.Enabled = true; Probably not as slick as a prompt, but it gets the job done.

like image 7
lincmercguy Avatar answered Oct 14 '22 13:10

lincmercguy