how to check if a datareader is null or empty

2019-03-08 23:55发布

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

12条回答
Summer. ? 凉城
2楼-- · 2019-03-08 23:59

Try this simpler equivalent syntax:

ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";
查看更多
神经病院院长
3楼-- · 2019-03-09 00:00

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:

public static class DataReaderExtensions
{
    public static bool IsDBNull( this IDataReader dataReader, string columnName )
    {
        return dataReader[columnName] == DBNull.Value;
    }
}

Kevin

查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-09 00:01

I also use OleDbDataReader.IsDBNull()

if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }
查看更多
beautiful°
5楼-- · 2019-03-09 00:01

AMG - Sorry all, was having a blond moment. The field "Additional" was added to the database after I had initially designed the database.

I updated all my code to use this new field, however I forgot to update the actual datareader code that was making the call to select the database fields, therefore it wasn't calling "Additional"

查看更多
再贱就再见
6楼-- · 2019-03-09 00:02

First of all, you probably want to check for a DBNull not a regular Null.

Or you could look at the IsDBNull method

查看更多
Juvenile、少年°
7楼-- · 2019-03-09 00:02

@Joe Philllips

SQlDataReader.IsDBNull(int index) requires the ordinal number of the column. Is there a way to check for nulls using Column Name, and not it's Ordinal Number?

查看更多
登录 后发表回答