C# DataRow Empty-check

Ash picture Ash · Feb 24, 2010 · Viewed 121.4k times · Source

I got this:

 DataTable dtEntity = CreateDataTable();
 drEntity = dtEntity.NewRow();

Then I add data to the row (or not). Lots of code, really don't know if there's anything inside the row. Depends on the input (i am importing from some files). I'd like to do something like:

 if (drEntity`s EVERY CELL IS NOT EMPTY)
 {
   dtEntity.Rows.Add(drEntity);
 }
 else
 {
   //don't add, will create a new one (drEntity = dtEntity.NewRow();)
 }

Is there some nice way to check if the DataRow's every cell is empty? Or I should foreach, and check them one by one?

Answer

Rob picture Rob · Feb 24, 2010

A simple method along the lines of:

bool AreAllColumnsEmpty(DataRow dr)
{
 if (dr == null)
 {
  return true;
 }
 else
 {
  foreach(var value in dr.ItemArray)
  {
    if (value != null)
    {
      return false;
    }
  }
  return true;
 }
}

Should give you what you're after, and to make it "nice" (as there's nothing as far as I'm aware, in the Framework), you could wrap it up as an extension method, and then your resultant code would be:

if (datarow.AreAllColumnsEmpty())
{
}
else
{
}