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?

oMatrix
  • 352
  • 1
  • 4
  • 10
  • 3
    What about `dr.Rows.Clear();`? – Shadow The GPT Wizard Jun 19 '12 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. – Tim Schmelter Jun 19 '12 at 14:31
  • @Tim won't the `Update()` of the table adapter delete all rows when the table is empty? – Shadow The GPT Wizard Jun 19 '12 at 14:33
  • possible duplicate of [Delete all rows in a datatable](http://stackoverflow.com/questions/955427/delete-all-rows-in-a-datatable) – Jon Egerton Jun 19 '12 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`](http://msdn.microsoft.com/en-us/library/system.data.datarowstate.aspx) are deleted via `DataAdapter.Update`. – Tim Schmelter Jun 19 '12 at 14:41

13 Answers13

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.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 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 Jun 19 '12 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(). – Ashish Gupta Jun 20 '12 at 03: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`. – Tim Schmelter Jun 20 '12 at 07: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 Jul 26 '13 at 15:36
  • does this require a commit? – JonathanPeel May 03 '17 at 08:02
  • No, unless you have an open transaction before this code. – Steve May 03 '17 at 08:21
  • Just found out that Oracle updatable views cannot be truncated in case anyone is trying to do that. – Hugh Seagraves Oct 18 '18 at 15:25
  • @Steve I am using the similar code ,but my veracode scan shows SQL Injection flaw as we are appending tablename in truncate statement which is coming from frontend ,can you let me know how can I prevent this ,I cannot create stored procedure as connection string context is dynamic where truncation should happen ,any other approach ?? – Code_1993 May 15 '20 at 20:02
23

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);
            }
        }
    }
}
krillgar
  • 12,596
  • 6
  • 50
  • 86
  • Both DataTable.Clear() and Rows.Clear() will just delete all rows from datatable but not the columns, refer to https://social.msdn.microsoft.com/Forums/en-US/be8066c7-0415-4977-9277-e73da98198b6/difference-between-datatableclear-and-datatablerowsclear?forum=csharplanguage – Carlos Liu Jun 16 '17 at 03: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 Jun 16 '17 at 10:54
  • 2
    sorry be fooled by the accepted answer in that thread ;-( but thanks for your clarification – Carlos Liu Jun 19 '17 at 03:06
15

As someone mentioned, just use:

dt.Rows.Clear()
Kreg
  • 647
  • 1
  • 6
  • 17
  • 6
    This will prevent the rows from being deleted since only DataRows with [`DataRowState=Deleted`](http://msdn.microsoft.com/en-us/library/system.data.datarowstate.aspx) are deleted via `DataAdapter.Update`. You're just removing them from the (in-memory) DataTable. – Tim Schmelter Jun 19 '12 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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Why dont you just do it in SQL?

DELETE FROM SomeTable
Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
Kell
  • 3,252
  • 20
  • 19
1

Just use dt.Clear()

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

dupe
  • 31
  • 1
1
TableAdapter.Update(dt.Clone());
//or
dt=dt.Clone();
TableAdapter.Update(dt);
//or
dt.Rows.Clear();
dt.AcceptChanges();
TableAdapter.Update(dt);
Ashik c
  • 11
  • 2
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.

Jake1164
  • 12,291
  • 6
  • 47
  • 64
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

Community
  • 1
  • 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 – Dave Hampel Sep 05 '19 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 ");
yozawiratama
  • 4,209
  • 12
  • 58
  • 106
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();
}
Mahmoud Sayed
  • 151
  • 2
  • 10
-1

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

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

Robert Iver
  • 711
  • 2
  • 9
  • 14
-2

Datatable.clear() method from class DataTable

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
Sebastian
  • 45
  • 2
  • 1
    This will prevent the rows from being deleted since only DataRows with [`DataRowState=Deleted`](http://msdn.microsoft.com/en-us/library/system.data.datarowstate.aspx) are deleted via `DataAdapter.Update`. You're just removing them from the (in-memory) DataTable. – Tim Schmelter Jun 19 '12 at 14:46