how to change an item index in listview?

18,580

You have to remove the selected item first, then re-add it at the new position.

E.g to move the item up 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);
}
Share:
18,580
Murhaf Sousli
Author by

Murhaf Sousli

Updated on June 15, 2022

Comments

  • Murhaf Sousli
    Murhaf Sousli almost 2 years

    I have a listView and two buttons (UP , DOWN) and i want to move the selected item up or down.
    I've thought about swapping between the selected item and the upper one.. but the code i tried .. doesn't make sense because index is readonly.
    also mines or sum doesn't owrk .. i can't mess with index at all.

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


    So .. how do i let the user the ability to change a ListViewItem index like how VB let us to change these item index [like in the pic]

    enter image description here

    thanks in advance ...