Reputation: 13296
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]
thanks in advance ...
Upvotes: 6
Views: 20405
Reputation: 71
In case of observable collections you are also able to call: .Move(currentindex, newindex);
Upvotes: 0
Reputation: 139
Following is an improvement to M4N answer to handle the re order of an item in the top of the list and make it in 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);
}
Upvotes: 0
Reputation: 96551
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);
}
Upvotes: 15