views:

145

answers:

2

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?

+3  A: 

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
}
Oskar Kjellin
A: 

The SelectedIndexChanged cannot be cancelled. So you only have one real option:

private int? currentIndex;
public void ListBox_SelectedIndexChanged(sender, EventArgs args) {
    if (currentIndex.HasValue && currentIndex.Value != listBox1.SelectedIndex) {
        var res = MessageBox.Show("Do you want to cancel edits?", "Cancel Edits", MessageBoxButtons.YesNo);
        if (res == DialogResult.Yes) {
            currentIndex = (listBox1.SelectedIndex == -1 ? null : (int?) listBox1.SelectedIndex);
        } else {
            listBox1.SelectedIndex = currentIndex.Value;
        }
    }
}
Obalix