27

I want to delete all rows in a datatable. I use something like this:

foreach (DataRow row in dt.Rows)
{
  row.Delete();
}
TableAdapter.Update(dt);

It works good but it takes lots of time if I have much rows. Is there any way to delete all rows at once?

5
  • 3
    What about dr.Rows.Clear();? Commented Jun 19, 2012 at 14:31
  • Do you want to remove them from the datatable or do you want to delete them from your dbms? @ShadowWizard: That would prevent them from being deleted from dbms. Commented Jun 19, 2012 at 14:31
  • @Tim won't the Update() of the table adapter delete all rows when the table is empty? Commented Jun 19, 2012 at 14:33
  • possible duplicate of Delete all rows in a datatable Commented Jun 19, 2012 at 14:33
  • 1
    @ShadowWizard: No, since you've removed all rows from the DataTable there's nothing to update anymore. Only rows in the DataTable with DataRowState=Deleted are deleted via DataAdapter.Update. Commented Jun 19, 2012 at 14:41

13 Answers 13

32

If you are running your code against a sqlserver database then
use this command

string sqlTrunc = "TRUNCATE TABLE " + yourTableName
SqlCommand cmd = new SqlCommand(sqlTrunc, conn);
cmd.ExecuteNonQuery();

this will be the fastest method and will delete everything from your table and reset the identity counter to zero.

The TRUNCATE keyword is supported also by other RDBMS.

5 years later:
Looking back at this answer I need to add something. The answer above is good only if you are absolutely sure about the source of the value in the yourTableName variable. This means that you shouldn't get this value from your user because he can type anything and this leads to Sql Injection problems well described in this famous comic strip. Always present your user a choice between hard coded names (tables or other symbolic values) using a non editable UI.

8
  • Thank you all for your quick answers. I used above method to delete all rows in DBMS and dt.Rows.Clear() after that to clear my table. It was great. Thank you all
    – oMatrix
    Commented Jun 19, 2012 at 15:17
  • 1
    @oMatrix, If you delete records from the database table (the way Steve suggested above), you need not do dt.Rows.Clear(). Commented Jun 20, 2012 at 3:55
  • @AshishGupta: dt.Rows.Clear() does nothing but removing the rows from the in-memory DataTable anyway. It will not delete rows on TableAdapter.Update(dt); since their DataRowState is unchanged. Commented Jun 20, 2012 at 7:19
  • What would you use for the connecton string on the command? If the DataTable is created in the code, I don't understand what I would need to connect to.
    – Patrick
    Commented Jul 26, 2013 at 15:36
  • does this require a commit? Commented May 3, 2017 at 8:02
24

This will allow you to clear all the rows and maintain the format of the DataTable.

dt.Rows.Clear();

There is also

dt.Clear();

However, calling Clear() on the DataTable (dt) will remove the Columns and formatting from the DataTable.

Per code found in an MSDN question, an internal method is called by both the DataRowsCollection, and DataTable with a different boolean parameter:

internal void Clear(bool clearAll)
{
    if (clearAll) // true is sent from the Data Table call
    {
        for (int i = 0; i < this.recordCapacity; i++)
        {
            this.rows[i] = null;
        }
        int count = this.table.columnCollection.Count;
        for (int j = 0; j < count; j++)
        {
            DataColumn column = this.table.columnCollection[j];
            for (int k = 0; k < this.recordCapacity; k++)
            {
                column.FreeRecord(k);
            }
        }
        this.lastFreeRecord = 0;
        this.freeRecordList.Clear();
    }
    else // False is sent from the DataRow Collection
    {
        this.freeRecordList.Capacity = this.freeRecordList.Count + this.table.Rows.Count;
        for (int m = 0; m < this.recordCapacity; m++)
        {
            if ((this.rows[m] != null) && (this.rows[m].rowID != -1))
            {
                int record = m;
                this.FreeRecord(ref record);
            }
        }
    }
}
3
  • Both DataTable.Clear() and Rows.Clear() will just delete all rows from datatable but not the columns, refer to social.msdn.microsoft.com/Forums/en-US/…
    – Carlos Liu
    Commented Jun 16, 2017 at 3:44
  • 1
    @CarlosLiu Thanks for the link! But according to the code shown in the link you shared (and I added it to my answer here), the DataTable Clear method will actually clear out the columns. Only the Rows.Clear() will keep the columns.
    – krillgar
    Commented Jun 16, 2017 at 10:54
  • 2
    sorry be fooled by the accepted answer in that thread ;-( but thanks for your clarification
    – Carlos Liu
    Commented Jun 19, 2017 at 3:06
15

As someone mentioned, just use:

dt.Rows.Clear()
1
  • 6
    This will prevent the rows from being deleted since only DataRows with DataRowState=Deleted are deleted via DataAdapter.Update. You're just removing them from the (in-memory) DataTable. Commented Jun 19, 2012 at 14:46
5

That's the easiest way to delete all rows from the table in dbms via DataAdapter. But if you want to do it in one batch, you can set the DataAdapter's UpdateBatchSize to 0(unlimited).

Another way would be to use a simple SqlCommand with CommandText DELETE FROM Table:

using(var con = new SqlConnection(ConfigurationSettings.AppSettings["con"]))
using(var cmd = new SqlCommand())
{
    cmd.CommandText = "DELETE FROM Table";
    cmd.Connection = con;
    con.Open();
    int numberDeleted = cmd.ExecuteNonQuery();  // all rows deleted
}

But if you instead only want to remove the DataRows from the DataTable, you just have to call DataTable.Clear. That would prevent any rows from being deleted in dbms.

1
  • Using Using is probably the friendliest way
    – msysmilu
    Commented Feb 26, 2016 at 16:15
2

Why dont you just do it in SQL?

DELETE FROM SomeTable
1

Just use dt.Clear()

Also you can set your TableAdapter/DataAdapter to clear before it fills with data.

1
  • It'll clear the DataTable but also prevents any rows from being deleted in the database (what OP wants imho). Commented Jun 19, 2012 at 15:04
1
TableAdapter.Update(dt.Clone());
//or
dt=dt.Clone();
TableAdapter.Update(dt);
//or
dt.Rows.Clear();
dt.AcceptChanges();
TableAdapter.Update(dt);
0

If you are really concerned about speed and not worried about the data you can do a Truncate. But this is assuming your DataTable is on a database and not just a memory object.

TRUNCATE TABLE tablename

The difference is this removes all rows without logging the row deletes making the transaction faster.

0

Here we have same question. You can use the following code:

SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["yourconnectionstringnamehere"].ConnectionString;
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "DELETE FROM [tablenamehere]";
SqlDataReader data = com.ExecuteReader();
con.Close();

But before you need to import following code to your project:

using System.Configuration;
using System.Data.SqlClient;

This is the specific part of the code that can delete all rows is a table:

DELETE FROM [tablenamehere]

This must be your table name:tablenamehere - This can delete all rows in table: DELETE FROM

1
  • the original question is 'How to delete rows from a DataTable' not 'delete rows from SQL'. I would say that krillgar has the best answer Commented Sep 5, 2019 at 18:43
0

I using MDaf just use this code :

DataContext db = new DataContext(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
db.TruncateTable("TABLE_NAME_HERE");
//or
db.Execute("TRUNCATE TABLE TABLE_NAME_HERE ");
0

Here is a clean and modern way to do it using Entity FW and without SQL Injection or TSQL..

using (Entities dbe = new Entities())
{
    dbe.myTable.RemoveRange(dbe.myTable.ToList());
    dbe.SaveChanges();
}
-1

Is there a Clear() method on the DataTable class??

I think there is. If there is, use that.

-2

Datatable.clear() method from class DataTable

1
  • 1
    This will prevent the rows from being deleted since only DataRows with DataRowState=Deleted are deleted via DataAdapter.Update. You're just removing them from the (in-memory) DataTable. Commented Jun 19, 2012 at 14:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.