Skip to content Skip to sidebar Skip to footer

How To Check If A Datareader Is Null Or Empty

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

Solution 1:

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

Solution 2:

if (myReader.HasRows) //The key Word is **.HasRows**

{

    ltlAdditional.Text = "Contains data";

}

else

{   

    ltlAdditional.Text = "Is null Or Empty";

}

Solution 3:

I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:

publicstaticclassDataReaderExtensions
{
    publicstaticboolIsDBNull(this IDataReader dataReader, string columnName )
    {
        return dataReader[columnName] == DBNull.Value;
    }
}

Kevin

Solution 4:

This is the correct and tested solution

if (myReader.Read())
{

    ltlAdditional.Text = "Contains data";
}
else
{   
    ltlAdditional.Text = "Is null";
}

Solution 5:

I also use OleDbDataReader.IsDBNull()

if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }

Post a Comment for "How To Check If A Datareader Is Null Or Empty"