0

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()

1
  • Check if the data row is not null with DataRow.IsNull(string columnName): if (!row.IsNull("ColumnName")){//Check for empty string here} Commented Nov 20, 2019 at 18:51

1 Answer 1

1

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()))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.