Cancelling the ListView SelectedIndexChanged event
I have a ListView that populates some fields whenever the user selects an item. However, if they change the data in the fields and then select a new item without saving, I want to display a message box that warns that their changes will be lost, and asks them to confirm whether to continue. Sounds simple.
Unfortunately, the ListView's SelectedIndexChanged event cannot be cancelled, and it's actually called for each change in the selection. So, for example, if item 1 is selected and the user then selects item 2, the event is called twice: once to remove the selection of item 1, and then to add the selection of item 2. If you go from having one item selected to having five (for example), the event fires to remove your original selection, and then again for each of your new selections - six hits in all.
Obviously, this makes it a bugger to determine when the event should be cancelled and reset back to the original. I obviously don't want my message box appearing six times....
Does anyone have a workaround for this?
Thanks...
Re: Cancelling the ListView SelectedIndexChanged event
This might be an old topic, but was never 'resolved' and I have exactly the same problem..
any ideas?
Re: Cancelling the ListView SelectedIndexChanged event
You can't cancel an event that is notifying you that something has happened. You can only cancel an event that is notifying you that something is going to happen. If you only want to display a message when an item is deselected then you have to detect when the number of selected items is reduced. It's too late to stop it at that point though.
The solution is to not use a ListView. Back in 2004, the alternative was a DataGrid, which did have its issues. Since .NET 2.0 though, we have had the DataGridView. That's the control you should be using.
Re: Cancelling the ListView SelectedIndexChanged event