Dealing with null values in SQLDataReader

Solution 4 involves adding columns within a loop, which results in the addition of the same column name repeatedly. On the other hand, Solution 2 suggests using one of the following methods to verify if the value is null and handle it accordingly.
The issue at hand is related to reading from a SQL datareader in C#, and transferring the column values to a dropdownlist.

Question:

The data is being read using

SqlDataReader

.

SqlDataReader reader;
connection.Open();
...
...
reader = command.ExecuteReader();
while(reader.Read())
{
     var address = new Adress()
      { 
        House = reader.GetString(1)
      }

What is causing an error with

reader.GetString(1)

?

Data is Null. This method or property cannot be called on Null values
.

Surprisingly data is available.

Kindly inform me of my errors in this situation.


Solution 1:

MSDN says

Before invoking this method, make sure to verify the absence of null values by placing a call to
isdbnull
.

The method does not provide protection against the existence of a null value in the row or field.

 var address = new Adress()
 { 
    House = reader.IsDbNull(1) ? "" : reader.GetString(1),
    ....
 }

Assuming you desire an empty string when the field is null, use the conditional operator’s true part to input your preferred value. Alternatively, you could throw your own exception if this is not the desired behavior.


Solution 2:


To determine if a value is null and deal with it accordingly, you can utilize any of the methods below:

if (reader.IsDBNull(1))

or

if (reader["FieldName"] == DBNull.Value)

Frequently Asked Questions

Posted in Uncategorized