Select the next item in a ListView

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

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

How to select the following in a ListView after deleting 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 an error

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

Thanks.

+4
source share
6 answers

ListView does not have a SelectedIndex property. It has the SelectedIndices property.

Gets the indices of the selected items in the control.

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

I had to add another line of code to the previous answer above, plus check that the counter 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; } 
+1
source

try using the listView1.SelectedIndices property

0
source

If you delete an item, the index of the β€œnext” item will be 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); 
0
source

I did it as follows:

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

I really 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 make it work, none of the other solutions worked for me.

Hope a more experienced programmer can give a better solution.

0
source

All Articles