C# 从 ListView 中删除所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1425623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove the Selected Item From ListView
提问by Binu
How can I remove a selected item from a listview?
如何从列表视图中删除选定的项目?
回答by Mitch
foreach (DataGridViewRow dgr in dgvComments.SelectedRows)
dgvComments.Rows.Remove(dgr);
回答by rahul
foreach ( ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
}
where listView1 is the id of your listview.
其中 listView1 是您的列表视图的 ID。
回答by AgentFire
listView1.Items.Cast<ListViewItem>().Where(T => T.Selected)
.Select(T => T.Index).ToList().ForEach(T => listView1.Items.RemoveAt(T))
回答by DeathDream
When there is just one item (Multiselect = false
):
当只有一项 ( Multiselect = false
) 时:
listview1.SelectedItems[0].Remove();
For more than one item (Multiselect = true
):
对于不止一项(Multiselect = true
):
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
}
回答by Marcin
listBox.Items.RemoveAt(listBox.SelectedIndex);
回答by Rushikumar
Yet another way to remove item(s) from a ListView
control (that has GridView
) (in WPF
)--
另一种从ListView
控件中删除项目的方法(具有GridView
)(在WPF
)--
var selected = myList.SelectedItems.Cast<Object>().ToArray();
foreach(var item in selected)
{
myList.Items.Remove(item);
}
where myList
is the name of your ListView
control
myList
你的ListView
控件名称在哪里
回答by dnl499
Well, although it's a lot late, I crossed that problem recently, so someone might cross with this problem again. Actually, I needed to remove all the selected items, but none of the codes above worked for me. It always throws an error, as the collection changes during the foreach. My solution was like this:
嗯,虽然晚了很多,但我最近遇到了这个问题,所以有人可能会再次遇到这个问题。实际上,我需要删除所有选定的项目,但上面的代码都不适合我。它总是抛出错误,因为在 foreach 期间集合发生了变化。我的解决方案是这样的:
while (listView1.SelectedIndex > 0)
{
listView1.Items.RemoveAt(listView1.SelectedIndex);
}
It won't throw the error as you get position of the last selected item (Currently), so even after you remove it, you'll get where it is now. When there is no items selected anymore, the SelectedIndex returns -1 and ends the loop. This way, you can make sure that there is no selected item anymore, nor that the code will try to remove an item in a negative index.
当您获得最后一个选定项目(当前)的位置时,它不会抛出错误,因此即使您将其删除,您也会得到它现在的位置。当不再选择任何项目时,SelectedIndex 返回 -1 并结束循环。这样,您可以确保不再有选定的项目,代码也不会尝试删除负索引中的项目。