webworm
webworm

Reputation: 11019

Validate that DataTable cell is not null or empty

I would like to check if the value in a Data Table cell is either null or empty/blank space. The String.IsNullOrEmpty() method does not work as the row["ColumnName"] is considered an object.

Do I need to do a compound check like the following or is there something more elegant?

if (row["ColumnName"] != DBNull.Value && row["ColumnName"].ToString().Length > 0)
{
  // Do something that requires the value to be something other than blank or null
}

I also thought of the following ...

if (!String.IsNullOrEmpty(dr["Amt Claimed"].ToString()))
{
  // Do something that requires the value to be something other than blank or null
}

but I figured if the value of the cell was null an exception would be thrown when trying to convert to a string using ToString()

Upvotes: 0

Views: 2018

Answers (1)

Asti
Asti

Reputation: 12677

A null value would be returned as DBNull, and not a null literal.

var tab = new System.Data.DataTable();
tab.Columns.Add("c1");
tab.Rows.Add();

tab.Rows[0]["c1"] = null;
tab.Rows[0]["c1"].GetType() //returns DBNull

And as the DBNull.ToString() is guaranteed to return an empty string, you can safely use !String.IsNullOrEmpty(value.ToString())).

You can always guard against not being sure if an object is null by simply using null coalescing.

!String.IsNullOrEmpty(value?.ToString()))

Upvotes: 1

Related Questions