Select next item in ListView

。_饼干妹妹 提交于 2019-12-22 08:55:13

问题


I have a method that removes currently selected item in a ListView

listView1.Items.Remove(listView1.SelectedItems[0]);

How do I select the next in the ListView after removing the selected one?

I tried something like

var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
listView1.SelectedItems[0].Index = index;

But I get the error

Property or indexer 'System.Windows.Forms.ListViewItem.Index' cannot be 
assigned to -- it is read only

Thank you.


回答1:


ListView doesn't have a SelectedIndex property. It has a SelectedIndices property.

Gets the indexes of the selected items in the control.

ListView.SelectedIndexCollection indexes = this.ListView1.SelectedIndices;

foreach ( int i in indexes )
{
 //
}



回答2:


I had to add one more line of code to a previous answer above, plus a check to verify the count was not exceeded:

int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
// Prevents exception on the last element:      
if (selectedIndex < listview.Items.Count)
{
  listview.Items[selectedIndex].Selected = true;
  listview.Items[selectedIndex].Focused = true;
}



回答3:


try use listView1.SelectedIndices property




回答4:


If you delete an item, the index of the "next" item is the same index as the one you just deleted. So, I would make sure you have listview1.IsSynchroniseDwithCurrentItemTrue = true and then

var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
CollectionViewSource.GetDefaultView(listview).MoveCurrentTo(index);



回答5:


I've done this in the following manner:

int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
listview.Items[selectedIndex].Selected = true;



回答6:


I actually had to do this:

        int[] indicies = new int[listViewCat.SelectedIndices.Count];
        listViewCat.SelectedIndices.CopyTo(indicies, 0);
        foreach(ListViewItem item in listViewCat.SelectedItems){
            listViewCat.Items.Remove(item);
            G.Categories.Remove(item.Text);
        }
        int k = 0;
        foreach(int i in indicies)
            listViewCat.Items[i+(k--)].Selected = true;
        listViewCat.Select();

to get it to work, none of the other solutions was working for me.

Hopefully, a more experienced programmer can give a better solution.



来源:https://stackoverflow.com/questions/15549921/select-next-item-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!