简体   繁体   中英

How to delete all rows from datatable

I want to delete all rows from datatable with rowstate property value Deleted.

DataTable dt;
dt.Clear(); // this will not set rowstate property to delete.

Currently I am iterating through all rows and deleting each row.

Is there any efficient way? I don't want to delete in SQL Server I want to use DataTable method.


We are using this way:

for(int i = table.Rows.Count - 1; i >= 0; i--) {
    DataRow row = table.Rows[i];
    if ( row.RowState == DataRowState.Deleted ) { table.Rows.RemoveAt(i); }
}

This will satisfy any FK cascade relationships, like 'delete' (that DataTable.Clear() will not):

DataTable dt = ...;
// Remove all
while(dt.Count > 0)
{
     dt.Rows[0].Delete();
}
dt.Rows.Clear();
dt.Columns.Clear();   //warning: All Columns delete
dt.Dispose();

由于您使用的是 SQL Server 数据库,因此我主张简单地执行 SQL 命令"DELETE FROM " + dt.TableName

I would drop the table, fastest way to delete everything. Then recreate the table.

您可以在 SQL Server db 上创建一个存储过程,删除表中的所有行,从 C# 代码中执行它,然后重新查询数据表。

我通常执行以下 SQL 命令:

DELETE FROM TABLE WHERE ID>0

I want to delete all rows from datatable with rowstate property value Deleted.

DataTable dt;
dt.Clear(); // this will not set rowstate property to delete.

Currently I am iterating through all rows and deleting each row.

Is there any efficient way? I don't want to delete in SQL Server I want to use DataTable method.


Here is the solution that I settled on in my own code after searching for this question, taking inspiration from Jorge's answer.

DataTable RemoveRowsTable = ...;
int i=0;
//Remove All
while (i < RemoveRowsTable.Rows.Count)
{
     DataRow currentRow = RemoveRowsTable.Rows[i];
     if (currentRow.RowState != DataRowState.Deleted)
     {
         currentRow.Delete();
     }
     else
     {
         i++;
     }
}

This way, you ensure all rows either get deleted, or have their DataRowState set to Deleted.

Also, you won't get the InvalidOperationException due to modifying a collection while enumerating, because foreach isn't used. However, the infinite loop bug that Jorge's solution is vulnerable to isn't a problem here because the code will increment past a DataRow whose DataRowState has already been set to Deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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