1

I get a row from table and some field of this row are null. How can I get these fields with SqlDataReader?

//so_type , so_read are null able 

while (reader.Read())
{
    s.id = (Int64)reader["so_id"];
    s.senderid = (Int64)reader["so_senderid"];
    s.body = (string)reader["so_body"];
    s.date = (string)reader["so_date"];
    s.isread = (bool)reader["so_read"];
    s.type = (int)reader["so_type"];
}

2 Answers 2

2

You can take advantage of C# generics to write a helper method which extracts the value or default for each column that can be null.

private static T GetValue<T>(object value)
{
    return value == DBNull.Value ? default(T) : (T) value;
}

while (reader.Read())
{
    s.id       = GetValue<long>(reader["so_id"]);
    s.senderid = GetValue<long>(reader["so_senderid"]);
    s.body     = GetValue<string>(reader["so_body"]);
    s.date     = GetValue<string>(reader["so_date"]);
    s.isread   = GetValue<bool>(reader["so_read"]);
    s.type     = GetValue<int>(reader["so_type"]);
}

This also assumes the value is already the correct type.

A more type safe implementation would be:

private static T GetValue<T>(object value)
{
    return value == DBNull.Value
           ? default(T)
           : (T) Convert.ChangeType(value, typeof(T));
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the IsDBNull method. Something like that:

int ordinal_so_type=reader.GetOrdinal("so_type");
//...
while(reader.Read()==true)
{
  //reading other columns here
  if (reader.IsDBNull(ordinal_so_type)==false)
  {
    s.type=reader.GetInt32(ordinal_so_type);
  }
  else
  {
    //do whatever you like if the so_type column is null
  }
}

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.