簡體   English   中英

DataReader返回DBNULL

[英]DataReader Returns DBNULL

我正在使用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
        });
    }
}

嘗試

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

希望這對您有幫助

請參閱GetValueOrDefault

使用DataReader中的IsDBNull()方法。

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

  }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM