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

/ / 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, we 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 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.  


Also Read

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

0 Comments