Search code examples
c#winformslistviewselectedindex

Select next item in ListView


I have a method that removes currently selected item in a ListView

listView1.Items.Remove(listView1.SelectedItems[0]);

How do I select the next in the ListView after removing the selected one?

I tried something like

var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
listView1.SelectedItems[0].Index = index;

But I get the error

Property or indexer 'System.Windows.Forms.ListViewItem.Index' cannot be 
assigned to -- it is read only

Thank you.


Solution

  • ListView doesn't have a SelectedIndex property. It has a SelectedIndices property.

    Gets the indexes of the selected items in the control.

    ListView.SelectedIndexCollection indexes = this.ListView1.SelectedIndices;
    
    foreach ( int i in indexes )
    {
     //
    }