Question

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.

Was it helpful?

Solution 2

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 )
{
 //
}

OTHER TIPS

I had to add one more line of code to a previous answer above, plus a check to verify the count was not exceeded:

int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
// Prevents exception on the last element:      
if (selectedIndex < listview.Items.Count)
{
  listview.Items[selectedIndex].Selected = true;
  listview.Items[selectedIndex].Focused = true;
}

try use listView1.SelectedIndices property

If you delete an item, the index of the "next" item is the same index as the one you just deleted. So, I would make sure you have listview1.IsSynchroniseDwithCurrentItemTrue = true and then

var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
CollectionViewSource.GetDefaultView(listview).MoveCurrentTo(index);

I've done this in the following manner:

int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
listview.Items[selectedIndex].Selected = true;

I actually had to do this:

        int[] indicies = new int[listViewCat.SelectedIndices.Count];
        listViewCat.SelectedIndices.CopyTo(indicies, 0);
        foreach(ListViewItem item in listViewCat.SelectedItems){
            listViewCat.Items.Remove(item);
            G.Categories.Remove(item.Text);
        }
        int k = 0;
        foreach(int i in indicies)
            listViewCat.Items[i+(k--)].Selected = true;
        listViewCat.Select();

to get it to work, none of the other solutions was working for me.

Hopefully, a more experienced programmer can give a better solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top