简体   繁体   English

为什么删除行后DataTable.Rows.Count不改变?

[英]Why does the DataTable.Rows.Count not change after deleting rows?

In my project I need to delete all records from a DataTable, so I tried this code : 在我的项目中,我需要删除DataTable中的所有记录,因此我尝试了以下代码:

while (DataTable1.Rows.Count > 0)
    DataTable1.Rows[0].Delete();

but this is an infinite loop, it seems that after the Delete() statement the Rows.Count does not changes. 但这是一个无限循环,似乎在Delete()语句之后, Rows.Count不会更改。

It appears the records are still there but marked for deletion. 似乎记录仍然存在,但标记为删除。
So I change my count to this : 因此,我将计数更改为:

int count = DataTable1.Select("", "", DataViewRowState.CurrentRows).Count();

So now I can change my loop like this 所以现在我可以像这样改变循环

int count = DataTable1.Select("","",DataViewRowState.CurrentRows).Count();
while (count > 0)
{
    DataTable1.Rows[0].Delete(); // THIS IS WRONG NOW
    count = DataTable1.Select("","",DataViewRowState.CurrentRows).Count();
}

Now the count does counts down as expected, but now I have a problem with the Rows[0].Delete() statement. 现在,计数确实按预期递减,但是现在我对Rows[0].Delete()语句有Rows[0].Delete()

It will delete the same row over and over again. 它将一遍又一遍删除同一行。

So my question is, how can I find the first row that is not deleted, and delete it ? 所以我的问题是,如何找到未删除的第一行并将其删除?
In other words, the line that is commented with // THIS IS WRONG NOW what can I use at that line ? 换句话说,用//注释的行现在不正确,我可以在该行使用什么?

Or is there a better way to do this ? 还是有更好的方法来做到这一点? I tried DataTable1.Clear() but that does not generates delete statements when doing adapter.Update(DataTable1); 我尝试了DataTable1.Clear(),但是在执行adapter.Update(DataTable1);时不会生成delete语句adapter.Update(DataTable1);

If you want to mark all rows deleted, why dont you use a plain foreach -loop? 如果要标记所有行已删除,为什么不使用普通的foreach -loop?

foreach(DataRow row in DataTable1.Rows) row.Delete();

Delete will mark this row as Deleted which is important for DataAdapters, they will call their DeleteCommand to delete this row from the database. Delete会将这一行标记为Deleted ,这对于DataAdapters很重要,它们将调用其DeleteCommand来从数据库中删除该行。 But it will not remove the row from the DataTable immediately. 但是它不会立即从DataTable删除该行。 If you want to remove it from the table use DataTable.Rows.RemoveAt(index) . 如果要从表中删除它,请使用DataTable.Rows.RemoveAt(index)

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

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