简体   繁体   中英

DataReader Returns DBNULL

I'm using DataReader to read the rows from my sqlcommand.

my problem is that i want return all columns from my database and error is that he found DBNull in one column.

how can i do to solved this?

Note: the column which return Null is of type string.

while(sqlDataReader.Read())
{
    if (sqlDataReader.HasRows)
    {
        mylist.Add(new User()
        {
            Id = (int)sqlDataReader["Id"],
            Name = (string)sqlDataReader["Name"],
            File= (string)sqlDataReader["File"]  <-- This is the one which contains some columns Null
        });
    }
}

Try

 File=(sqlDataReader["File"] as string).GetValueOrDefault("");

Hope this may help you

Refer GetValueOrDefault

Use IsDBNull() method from DataReader.

if (sqlDataReader.HasRows)
{
  while(sqlDataReader.Read())
  {
    if(!sqlDataReader.IsDBNull(1)) //pass the column index.
    {
        object value=sqlDataReader[1];
    }

  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM