C# – how to check if a datareader is null or empty

cnullsqldatareader

I have a datareader that return a lsit of records from a sql server database. I have a field in the database called "Additional". This field is 50% of the time empty or null.

I am trying to write code that checks if this field isnull. The logic behind this is:
If the field "Additional" contains text then display the info otherwise hide the field.

I have tried:

if (myReader["Additional"] != null)
{
    ltlAdditional.Text = "contains data";
}
else
{
     ltlAdditional.Text = "is null";
}

The above code gives me this error:

Exception Details: System.IndexOutOfRangeException: Additional

Any help would be greatly appreciated…


See Also:

Check for column name in a SqlDataReader object

Best Answer

if (myReader["Additional"] != DBNull.Value)
{
    ltlAdditional.Text = "contains data";
}
else
{
     ltlAdditional.Text = "is null";
}