webworm
webworm

Reputation: 11019

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?

Upvotes: 0

Views: 1318

Answers (3)

haldo
haldo

Reputation: 16711

You could instead use the Field<T>() method of the DataRow:

bool isEmpty = String.IsNullOrEmpty(row.Field<string>("MyColumn")); 

This provides strongly typed access to the row values.

You can use it with other types too, so no need to parse int or DataTime, for example.

var myDate = row.Field<DateTime>("MyDate");   // DateTime
var myInt = row.Field<int>("MyInt");          // int

It also works with nullable types:

var myDate = row.Field<DateTime?>("MyDate");  // DateTime? (Nullable)
if (myDate.HasValue) 
{
    ...
}

Upvotes: 1

Broots Waymb
Broots Waymb

Reputation: 4826

Basically just adding this for the sake of completeness... but if for some reason you aren't using C# 6 or above, you can always do it the "old fashioned way":

bool isEmpty = row["MyColumn"] == null || string.IsNullOrEmpty(row["MyColumn"].ToString());

Upvotes: 1

Jawad
Jawad

Reputation: 11364

Change your statement to this,

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

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

Upvotes: 4

Related Questions