Want a free Ebook & latest Update Subscribe Now
  [email protected]      beta
Donate

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

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 Asp.net 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)
     {
        dt.Rows[i].Delete();
      }
 }
 dt.AcceptChanges();
 return dt;

 

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

Delete empty rows from datatable

 

Also Read

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }



Post Comment


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