[英]If strings are nullable by default, why do i get Unable to cast object of type 'System.DBNull' to type 'System.String'.?
I have seen similar threads like this where the solution is a tertiary if. 我也有类似的线程像这样在解决方案是一个三级如果。
My question is, why even get such an error if Strings are nullable? 我的问题是,如果字符串可为空,为什么还要得到这样的错误?
I am reading a value of a text column in access using ado.net. 我正在使用ado.net读取访问中的文本列的值。 Whenever there is a row with an empty text column i get that error. 每当有一行带有空文本列的行时,我都会收到该错误。
Culprit: 罪魁祸首:
while (dr.Read())
{
UserList.Add(new UserInfo()
{
.
DestributionGroup = (string)dr["Destribution Group"]
.
}
}
class UserInfo
{
.
public string DestributionGroup;
.
}
Edit: 编辑:
So in other words I have to convert all of my strings that I am reading from the DB into a line similar to this? 所以换句话说,我必须将我从数据库读取的所有字符串转换成与此类似的行?
return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString ()
No other way around it? 没有其他办法吗?
如果您不介意在dr [“ Destribution Group”]为DBNull.Value时将DestributionGroup设置为null,则可以使用此方法:
DestributionGroup = dr["Destribution Group"] as string;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.