Search code examples
c#nullisnullorempty

String.IsNullOrEmpty check with Data Table cell


If I have a Data Table and I want to see if the value contained within a specific cell is empty I would use this.

foreach(DataRow row in DataTable.Rows)
{
    bool isEmpty = String.IsNullOrEmpty(row["MyColumn"].ToString());
}

but what happens if the value in row["MyColumn"] is null. Wouldn't the .ToString() throw an exception? Yet when I try the following ..

bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]);

I get an invalid argument exception because the IsNullOrEmpty() method is looking for a string object.

So what is the proper way to check if a specific cell in a Data Table is empty or null?


Solution

  • Change your statement to this,

    bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]?.ToString());
    

    ?. means run the process .ToString() only if row["MyColumn"] is not null.