2013-09-27 40 views
0

我正在使用DataReader从我的sqlcommand中读取行。DataReader返回DBNULL

我的问题是,我想返回我的数据库中的所有列 ,错误是他在一列中找到了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 
     }); 
    } 
} 

回答

2

使用IsDBNull以便在()方法从DataReader的。

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

    } 
} 
+0

这解决了我的问题..非常感谢你 – user2232273

3

尝试

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

希望这可以帮助你

参考GetValueOrDefault

+0

我不能选择扩展名GetValueorDefault,但“CreativeManix”的答案已经解决了它。不过谢谢你的帮助..非常感谢你.. +1 – user2232273