How to swap two rows in a ListView data view?

What would be the easiest way to swap items in a ListView?

My scenario is to have a way of posting.

Example: I wanted to change an element in the first row or index 0 to the second row or index 1

List of items in a list of items:

  • | Hi | hi |
  • | 12345 | 12 |

After exchange

  • | 12345 | 12 |
  • | Hi | hi |

How can I do that?

+4
source share
3 answers

You tried to remove ListViewItem n from ListView, keeping a link to it, of course, then you can insert it at position n-1.

I have not tried, but if I remember well, there is ListView.Items.Insert or AddAt, which takes an index as a parameter and ListViewItem to add.

+4
source

Well, you could create a function that accepts two indexes that you want to exchange and exchange in trade like this:

private: void Swapinlistbox( int indexA, int indexB) { ListViewItem item = listView1.Items[indexA]; listView1.Items.Remove(item); listView1.Items.Insert(indexB, item); } 
+1
source

Common Swap Method for ListView:

  private void SwapListView(ListView list, ListViewItem itemA, ListViewItem itemB) { int bIndex = itemB.Index; int aIndex = itemA.Index; list.Items.Remove(itemB); list.Items.Remove(itemA); list.Items.Insert(bIndex, itemA); list.Items.Insert(aIndex, itemB); } 
0
source

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


All Articles