asp.net DataReader返回DBNULL

neekobn8  于 11个月前  发布在  .NET
关注(0)|答案(2)|浏览(96)

我使用DataReader从我的sqlcommand读取行。
我的问题是,我想返回所有列从我的数据库和错误是,他发现DBNull在一列。
我该怎么做才能解决这个问题呢?
注意:返回Null的列是字符串类型。

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
        });
    }
}

字符串

lb3vh1jj

lb3vh1jj1#

使用DataReader中的 IsDBNull() 方法。

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

  }
 }

字符串

bihw5rsg

bihw5rsg2#

试试看:

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

字符串
请参阅GetValueOrDefault的文档。

相关问题