Abraham
Abraham

Reputation: 1259

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.

Upvotes: 4

Views: 8348

Answers (6)

Crazy Cat
Crazy Cat

Reputation: 1452

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;
}

Upvotes: 2

user2803368
user2803368

Reputation: 31

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.

Upvotes: 0

Ekster
Ekster

Reputation: 353

I've done this in the following manner:

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

Upvotes: 0

Barracoder
Barracoder

Reputation: 3764

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);

Upvotes: 0

David
David

Reputation: 16277

try use listView1.SelectedIndices property

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

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

Upvotes: 1

Related Questions