Reputation: 5352
I've the following code that Clones/makes a copy the selected ListView item, removes the Selected item, and then re-inserts the copied Item in a new position in the ListView.
private void btnUp_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 1)
{
int iIndex = listView1.FocusedItem.Index;
if (iIndex > 0)
{
ListViewItem oListViewItem = (ListViewItem)listView1.FocusedItem.Clone();
listView1.Items.Remove(listView1.FocusedItem);
listView1.Items.Insert(iIndex - 1, oListViewItem);
}
}
}
The code works fine and the item is moved and the list updated. However, I'm wanting the newly inserted Item to remain selected. I tried
listView1.Items[iIndex - 1].Selected = true;
but this doesn't have the desired affect.
What else can I try ?
Upvotes: 2
Views: 2574
Reputation: 216243
If you add the Selected = true
to the newly inserted item index then your code should work as expected. But when you click on the button, the focus goes to the pressed button and under the default properties the ListView.HideSelection is set to True. So you don't see any item selected. If you press TAB on your form until the ListView is again the focused control, your ListViewItem should be showed as selected.
If you want to show some form of (dimmed) selection even when the control is not focused then set
listView1.HideSelection = false;
However, if I understand what you are trying to do (moveup an item) then you should change your code to use the SelectedItems[0] element instead of the FocusedItem
if (listView1.SelectedItems.Count == 1)
{
int iIndex = listView1.SelectedItems[0].Index;
if (iIndex > 0)
{
ListViewItem oListViewItem = (ListViewItem)listView1.SelectedItems[0].Clone();
listView1.SelectedItems[0].Remove();
listView1.Items.Insert(iIndex -1, oListViewItem);
listView1.Items[iIndex -1].Selected = true;
}
}
Upvotes: 4
Reputation: 380
You might want to try using the IndexOf method to get the index of the inserted item.
listView.Items[listView.Items.IndexOf(oListViewItem)].Selected = true;
Hope this helps.
Upvotes: -1