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 emp
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
I also use OleDbDataReader.IsDBNull()
if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }
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.
This is the correct and tested solution
if (myReader.Read())
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null";
}
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.
First of all, you probably want to check for a DBNull
not a regular Null
.
Or you could look at the IsDBNull
method