How to change the index of an item in a list?

I have a listView and two buttons (UP, DOWN), and I want to move the selected item up or down.
I was thinking about exchanging between the selected item and the top ... but the code I tried .. makes no sense, because the index is read-only.
also mines or amounts are not owrk .. i cant mess with the index at all.

private void btnDown_Click(object sender, EventArgs e) { listView1.SelectedItems[0].Index--; // It ReadOnly. } 


So, how can I let the user change the index of the ListViewItem, for example, how VB allows us to change this index of the element [as in the picture]

enter image description here

thanks in advance...

+4
source share
3 answers

You must first delete the selected item and then add it to the new position again.

For example, to move an item one position:

 var currentIndex = listView1.SelectedItems[0].Index; var item = listView1.Items[index]; if (currentIndex > 0) { listView1.Items.RemoveAt(currentIndex); listView1.Items.Insert(currentIndex-1, item); } 
+13
source

The following is an improvement on the M4N response to handle ordering an item at the top of the list and creating it at the bottom of the list.

 int currentIndex = listView1.SelectedItems[0].Index; ListViewItem item = listView1.Items[currentIndex]; if (currentIndex > 0) { listView1.Items.RemoveAt(currentIndex); listView1.Items.Insert(currentIndex - 1, item); } else { /*If the item is the top item make it the last*/ listView1.Items.RemoveAt(currentIndex); listView1.Items.Insert(listView1.Items.Count, item); } 
0
source

In the case of observable collections, you can also call: .Move (currentindex, newindex);

MSDN

0
source

Source: https://habr.com/ru/post/1400941/


All Articles