user1893874
user1893874

Reputation: 843

SqlDataReader - This method or property cannot be called on Null values

I am using SqlDataReader to read the data

SqlDataReader reader;
connection.Open();
...
...
reader = command.ExecuteReader();

while(reader.Read())
{
     var address = new Adress()
      { 
        House = reader.GetString(1)
      }

Why is reader.GetString(1) throwing an error

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

Surprisingly data is available.

Please let me know what I'm doing wrong here..

Upvotes: 0

Views: 3247

Answers (2)

Steve
Steve

Reputation: 216293

MSDN says

Call IsDBNull to check for null values before calling this method.

This means that the method doesn't protect your code from the presence of a null value in the row/field

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

Of course this assumes that you want an empty string in case your field is null, if this is not the case then you could put whatever you like in the true part of the conditional operator or throw your own exception.

Upvotes: 3

Rono
Rono

Reputation: 3361

You can use either of the following to check if the value is null and handle it appropriately:

if (reader.IsDBNull(1))

or

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

Upvotes: 1

Related Questions