meetjaydeep
meetjaydeep

Reputation: 1850

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.


Upvotes: 4

Views: 42783

Answers (8)

andrew0007
andrew0007

Reputation: 1265

I typically execute the following SQL command:

DELETE FROM TABLE WHERE ID>0

Upvotes: 1

user3779649
user3779649

Reputation: 21

dt.Rows.Clear();
dt.Columns.Clear();   //warning: All Columns delete
dt.Dispose();

Upvotes: 2

Yetti
Yetti

Reputation: 1720

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.

Upvotes: 0

Jorge
Jorge

Reputation: 31

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();
}

Upvotes: 3

Beth
Beth

Reputation: 9617

You could create a stored procedure on the SQL Server db that deletes all the rows in the table, execute it from your C# code, then requery the datatable.

Upvotes: 0

UnixShadow
UnixShadow

Reputation: 1244

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

Upvotes: 0

Roman Starkov
Roman Starkov

Reputation: 61512

Since you're using an SQL Server database, I would advocate simply executing the SQL command "DELETE FROM " + dt.TableName.

Upvotes: 0

TcKs
TcKs

Reputation: 26632

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); }
}

Upvotes: 5

Related Questions