简体   繁体   中英

C#: bizzare multiple event firing for listview on SelectedIndexChanged

If I put a listview component into a windows form and add bellow code to it's SelectedIndexChanged event:

MessageBox.Show("Fired!");
foreach (int selectedIndex in listView1.SelectedIndices)
{
    listView1.Items[selectedIndex].Selected = false;
    listView1.Items[selectedIndex].Focused = false;
}

the message box will be shown 4 times! why is that?

Note : I use the loop to clear the selected items in listview

You should not change the selection in a SelectedIndexChanged event. More generally, you should not change a property inside of a notification that the property has been changed .

If you need to change a property in response to a notification, look to handle the corresponding *Changing event. Rather than being a notification that something has changed (which comes after the fact), it is a notification that something is about to change (which comes before the fact). In the SelectedIndexChanging event, you have a couple of different options to alter the course of events:

  1. You can set the e.Cancel property to true , which will do just as it says. It will cancel the event and prevent the selected index from changing.
  2. You can use the e.NewSelectedIndex property to alter the selection. Just set this property to the index of the item that you want to be selected.

And if you want to clear the selected items in a ListView in response to some other event ( eg , a click on a "Clear Selection" button that is not part of the ListView, or a similar context menu item), you don't need a loop at all. Just clear the control's SelectedItems collection: myListView.SelectedItems.Clear() . Again, you can't do this in response the SelectedIndexChanged event, or you'll have the same problem of triggering a bunch of notifications.

Honestly, though, the code you've written here makes no sense. Why would you want to clear all selected items when the user tries to select an item? If you don't want to allow selection, disable the control by setting its Enabled property to false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM