[英]DBNull Error when adding new column to a datatable
I know there are A LOT of posts about this already, but I didn't find anything that helped me understand or fix my issue.我知道已经有很多关于此的帖子,但我没有找到任何可以帮助我理解或解决我的问题的帖子。 I have a database filling a datatable.
我有一个填充数据表的数据库。 I am now trying to add a new column and set the value of the column row equal to 1 or 0 depending on the little formula below:
我现在正在尝试添加一个新列,并根据下面的小公式将列行的值设置为 1 或 0:
dt.Columns.Add("pViolation");
foreach (DataRow row in dt.Rows)
{
/*exception thrown here*/ if (Convert.ToDecimal(row["oPrice"]) < Convert.ToDecimal(row["pPrice"]))
{
row["pViolation"] = 1;
}
else
{
row["pViolation"] = 0;
}
}
I keep getting this error:我不断收到此错误:
System.InvalidCastException: 'Object cannot be cast from DBNull to other types.'
System.InvalidCastException: '对象不能从 DBNull 转换为其他类型。'
Columns oPrice
and pPrice
have decimal values filled in them for each column already, so I am not casting them from null to a decimal. oPrice
和pPrice
列已经为每列填充了十进制值,所以我不会将它们从 null 转换为小数。 Can someone tell me what I am doing wrong?有人能告诉我我做错了什么吗?
It's throwing the exception because either row["oPrice"]
or row["pPrice"]
is null in the database.它抛出异常,因为数据库中的
row["oPrice"]
或row["pPrice"]
为空。
You can check for null first, but you'll need to decide how to handle null values:您可以先检查 null,但您需要决定如何处理 null 值:
// check if either value is null
if (row["oPrice"] == DBNull.Value || row["pPrice"] == DBNull.Value)
{
// what do you want to do when one value (or both values) is null?
}
else if (Convert.ToDecimal(row["oPrice"]) < Convert.ToDecimal(row["pPrice"]))
{
row["pViolation"] = 1;
}
else
{
row["pViolation"] = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.