简体   繁体   English

删除GridView中的选定项目

[英]Delete selected items in a GridView

IList<object> itemsSelected = MyGrid.SelectedItems;

foreach (object itemSelected in itemsSelected)
{
   MyGrid.SelectedItems.Remove(itemSelected);
}

I try remove selected items from a GridView but not all selected items are removed. 我尝试从GridView中删除所选项目,但不会删除所有选定项目。 Could someone help me? 有人能帮助我吗?

object[] itemsSelected = MyGrid.SelectedItems.ToArray<object>();
        foreach (object item in itemsSelected)
        {
            MyGrid.Items.Remove(item);
        }

I had the exact problem as well. 我也遇到了确切的问题。 I wrote something like this but it didn't delete all items too, just some of them : 我写了这样的东西,但它也没有删除所有项目,只是其中一些:

foreach(var item in MyGridView.SelectedItems)
{
     MyGridView.Items.Remove(item);
}

But write this which will delete all your selected items for sure : 但写下这将删除所有您选择的项目肯定:

while (YourGridView.SelectedItems.Count != 0)
{
    YourGridView.Items.Remove(YouGridView.SelectedItem);
}

there isn't exception, when you use foreach with SelectedItems? 当你使用foreach和SelectedItems时,没有例外吗? When you remove item, SelectedItems array is modified and foreach throws an exception. 删除item时,SelectedItems数组被修改,foreach抛出异常。 (Though I've tried on ListBox control). (虽然我尝试过ListBox控件)。 Try to use for-operator and remove items from last to first by index. 尝试使用for-operator并从索引中删除last到first的项目。

Based on your answers in the comments, I assume you are working on a C# winforms application. 根据您在评论中的答案,我假设您正在使用C#winforms应用程序。

Is it possible that what you are actualy using is a ListBox and not a GridView ? 您实际使用的是ListBox不是 GridView吗?

If that is so, you should use the ClearSelected() method which unselects all items in the ListBox . 如果是这样,您应该使用ClearSelected()方法取消选择ListBox所有项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM