How to Swap Two Rows of listview in Upward/Downward Direction

In this article, I am describing how two data rows swap within a list view by using C#. To solve this task, I searched so many things but did not find a useful link. In the end, I develop own code which performs this task successfully.

I get the index of above selected data item and then make two variables of String and get values of selected item and above of selected item. Then assign values; give value of selected item to above of selected item and value of above selected item to selected item. To make a listviewItem object tmp and add them into listviewItem Object. And it's working. This is code for upward button for downward only change one thing; change sign of - into +. It will work for downward.

 

Upward Direction:

 

int indexs = (listview_urls.SelectedItems[0].Index) - 1;

if (indexs > -1)

{

    string s = listview_urls.SelectedItems[0].SubItems[1].Text;

    string S2 = listview_urls.Items[indexs].SubItems[1].Text;

    listview_urls.SelectedItems[0].SubItems[1].Text = S2;

    listview_urls.Items[indexs].SubItems[1].Text = s;

    ListViewItem tmp = new ListViewItem();

    tmp.SubItems.Add(S2);

    tmp.SubItems.Add(s);
    ListViewItem nextItem = listView_Scheduler.Items[indexs];
    nextItem.Selected =
true;
    listView_Scheduler.Items[indexs + 1].Selected =
false;
    listView_Scheduler.Focus();
    listView_Scheduler.Refresh();
}

else

{

    MessageBox.Show("Sorry!Can't move further upward");

}

 

Downward Direction:

 

int indexs = (listview_urls.SelectedItems[0].Index) + 1;

if (indexs < listview_urls.Items.Count)

{

    string s = listview_urls.SelectedItems[0].SubItems[1].Text;

    string S2 = listview_urls.Items[indexs].SubItems[1].Text;

    listview_urls.SelectedItems[0].SubItems[1].Text = S2;

    listview_urls.Items[indexs].SubItems[1].Text = s;

    ListViewItem tmp = new ListViewItem();

    tmp.SubItems.Add(S2);

    tmp.SubItems.Add(s);
   
ListViewItem nextItem = listView_Scheduler.Items[indexs];
   
nextItem.Selected =
true;
    listView_Scheduler.Items[indexs - 1].Selected =
false;
    listView_Scheduler.Focus();
   
listView_Scheduler.Refresh();
}

else

{

    MessageBox.Show("Sorry!Can't move further Downward");

}

 

Try it and enjoy it.