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条回答
劳资没心,怎么记你
2楼-- · 2019-03-09 00:06

This is the correct and tested solution

if (myReader.Read())
{

    ltlAdditional.Text = "Contains data";
}
else
{   
    ltlAdditional.Text = "Is null";
}
查看更多
Rolldiameter
3楼-- · 2019-03-09 00:19
if (myReader.HasRows) //The key Word is **.HasRows**

{

    ltlAdditional.Text = "Contains data";

}

else

{   

    ltlAdditional.Text = "Is null Or Empty";

}
查看更多
乱世女痞
4楼-- · 2019-03-09 00:19

In addition to the suggestions given, you can do this directly from your query like this -

SELECT ISNULL([Additional], -1) AS [Additional]

This way you can write the condition to check whether the field value is < 0 or >= 0.

查看更多
别忘想泡老子
5楼-- · 2019-03-09 00:19

I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:

DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");

using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.

查看更多
劳资没心,怎么记你
6楼-- · 2019-03-09 00:22

This

Example:

objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
查看更多
趁早两清
7楼-- · 2019-03-09 00:25
if (myReader["Additional"] != DBNull.Value)
{
    ltlAdditional.Text = "contains data";
}
else
{
     ltlAdditional.Text = "is null";
}
查看更多
登录 后发表回答