How to delete empty/null rows from DataTable in C#

satinder singh / Updated : / 0 Comments

Delete null rows: Here in this article, we learn how to delete blanks rows from DataTable in C#. I was working with excel file where have to import data from an Excel sheet to database. For import have to read excel data to DataTable then save it to the database. Then I figure out that our DataTable contain many blank or empty rows as excel sheet contains empty records. These empty rows are unnecessarily getting added into our database and make our database ugly.

To avoid this, have to delete blank or null rows before adding it to the database.

About DataTable:

A DataTable is an in-memory representation of a single database table. DataTable class stores rows and columns of data.

It is a central object in the ADO.NET library and part of the System.Data namespace. We add, select and iterate over stored data.


DataTable with empty rowsDataTable having null empty rows

Also Read:  Remove Duplicate rows records from DataTable c#

C# code to delete empty rows from DataTable.

First, we have to iterate over DataTable for this we use a reverse for loop, here we checked for the 1st column if its blanks will delete that row. And at the end with AcceptChanges(), our changes get saved. This is how we get cleaned datatable .i.e removed empty or blank entries.

Our final code looks like as written below.

for (int i = dt.Rows.Count - 1; i >= 0; i--)
     if (dt.Rows[i][1] == DBNull.Value)
 return dt;


Output: Our final DataTable look like as shown in below image.

Delete empty rows from datatable


Also Read

Post Comment

Your email address will not be published. Required fields are marked *