我有一个DataGrid theDataGrid
绑定到DataSet ds
包含表的 WPF。我想让用户通过首先在网格中选择它们然后按下一个按钮(位于数据网格之外的某个位置)来删除线。我终于到达了以下代码行,它们可以满足我的需求,但我认为它们相当丑陋:
DataSet ds = new DataSet();
...
// fill ds somehow
...
private void ButtonClickHandler(object Sender, RoutedEventArgs e)
{
List<DataRow> theRows = new List<DataRow>();
for (int i = 0; i < theDataGrid.SelectedItems.Count; ++i)
{
// o is only introduced to be able to inspect it during debugging
Object o = theDataGrid.SelectedItems[i];
if (o != CollectionView.NewItemPlaceholder)
{
DataRowView r = (DataRowView)o;
theRows.Add(r.Row);
}
}
foreach(DataRow r in theRows)
{
int k = ds.Tables["producer"].Rows.IndexOf(r);
// don't remove() but delete() cause of update later on
ds.Tables[0].Rows[k].Delete();
}
}
有一个更好的方法吗?例如,只需要一个循环而无需NewItemPlaceHolder
显式检查,或者可能是一种更有效的方式来访问要删除的行?
(我已经发现我不能在第一个循环中从 ds 中删除任何内容,因为theDataGrid.SelectedItems.Count
每次执行循环时都会更改......)