我有一个WPF DataGrid theDataGrid
绑定到包含表格的DataSet ds
。我想让用户首先在网格中选择它们然后按一个按钮(位于数据网格之外的某个位置)来删除行。我终于到达了以下代码行,这些代码行做了我想做的事情,但我觉得它很难看:
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
都会改变...)
答案 0 :(得分:1)
要删除按钮上的所选行,您可以尝试:
private void ButtonClickHandler(object sender, RoutedEventArgs e)//Remove row selected
{
DataRowView dataRow = (DataRowView)dataGridCodes.SelectedItem; //dataRow holds the selection
dataRow.Delete();
}
答案 1 :(得分:0)
我认为它仅适用于一个循环:
int count=theDataGrid.SelectedItems.Count;
int removedCount=0;
while (removedCount < count)
{
try{
Object o = theDataGrid.SelectedItems[0];
}
catch{ break;}
if (o == CollectionView.NewItemPlaceholder)
continue;
DataRowView r = (DataRowView)o;
r.Row.Delete();
removedCount++;
}
答案 2 :(得分:0)
您可以通过向后迭代来删除双循环:
private void ButtonClickHandler(object Sender, RoutedEventArgs e) {
for (int i = theDataGrid.SelectedItems.Count-1; i>=0; --i)
if (theDataGrid.SelectedItems[i] != CollectionView.NewItemPlaceholder)
ds.Tables[0].Rows[i].Delete();
}