WPF DataGrid 删除所选项目
最近,我一直在开发一个项目,该项目以编程方式将数据导入到 WPF DataGrid 中。
我几乎完成了该项目,但我遗漏的是一个用于删除所选单元格的按钮,这就是我陷入困境的地方!
我使用 DataGrids 的基本知识编写了这段代码:
var grid = dataGrid1;
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
grid.Items.Remove(grid.SelectedItems[i]);
};
}
可以很好地仅删除选定的项目,就像 CurrentItem 一样,但它不会删除超过 2 个选定的项目!
我的 DataGrid 至少应包含 100 个项目。我添加了一个删除所有选项,但这也是必要的。
如果有人给我解决方案,我将不胜感激。
Recently I've been working on a project which imports data programmicaly into a WPF DataGrid.
I'm almost done with the project but the thing that I left out was a button to remove selected cells and this is where I'm stuck!
I wrote this code using my basic knowledge of DataGrids:
var grid = dataGrid1;
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
grid.Items.Remove(grid.SelectedItems[i]);
};
}
Works fine on removing only the item selected just like CurrentItem but it doesn't remove anymore than 2 selected items!
The DataGrid I have should at least contain a minimum of 100 items. I've added a remove all option but this is also necessary.
I'll be thankful if anyone gives me the solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
通过删除所选项目,您将更改
SelectedItems
集合。您应该先复制它,然后开始删除。By removing selected item you are changing
SelectedItems
collection. You should copy it first and then start removing.这对我来说也很有效。
This also worked well for me.
您在这里犯的错误是在循环期间删除项目,这会扰乱循环计数,因此制作一个复制网格并从中删除选定项目,然后将其与原始网格相等。
看看这个
The mistake you are doing here you are removing items during loop whaich is messing with loop count so make a copy grid and remove selecteditem from it and then equlize it by the orignal one..
Check this out
这对我有用......
This worked for me...
使用 SelectedItem 而不是 SelectedIndex 的 while 循环
A while loop using the SelectedItem instead of the SelectedIndex
我和作者有同样的问题。并找到了相当漂亮的(我认为)解决方案。
所以主要问题是 SelectedItems 动态的,当你删除一行时,它会再次重新计算。
所以我的代码如下所示:
因此,每次 for 循环执行步骤 1 时,datagrid1.SelectedItems.Count 都会减 1,并且变量 i 会增加。
I have stack with the same problem as an author. And found quite beautiful (I think) solution.
And so the main problem is that the SelectedItems dynamic, and when you delete one row, it is recalculated again.
And so my code looks like this:
So, every time the for loop is doing step 1, datagrid1.SelectedItems.Count is decreased by 1, and the variable i increases.
我的解决方案(如果您使用的是 adonet 且 autogeneratecolumns=true);
My solution (if you are using adonet with autogeneratecolumns=true);
这对我有用......
This worked for me...