0

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..

3
  • 1
    What do you mean with data is available? The error message is pretty clear Commented Jan 5, 2016 at 20:10
  • I added a check to see data exists or not by using HasRows. .... if (reader.HasRows) is returning TRUE but when I try to access the data it is throwing this error. Commented Jan 5, 2016 at 20:29
  • Just to ask, are you sure you're not wanting to get GetString(0)? GetString is zero-indexed and the first string in your return will be index 0 not a 1. Commented Jan 5, 2016 at 20:37

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

reader.HasRows is returning True here. then why this error msg ?
It seems that you have a misunderstanding about the workings of the datareader. Checking HasRows is correct but redundant. It tells you if there are Rows and in your context is useless because Read tells you the same thing. GetString takes a field from the current Row (the field at position 1) and if this field contains a DbNull.Value then you get the error for that line.
Personally I do reader[1] as String that gives you null if the database value was DbNull.Value or the string if it was a normal string.
Interesting, I am curious if this is better in terms of response time to get out the data.
Never been in a situation where the performance was marginal enough to test the difference.
|
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.