简体   繁体   English

将新列添加到数据表时出现 DBNull 错误

[英]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. oPricepPrice列已经为每列填充了十进制值,所以我不会将它们从 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.

相关问题 在数据表中添加新行时,将逗号分隔值添加到数据表列的更好方法 - Better way to add comma separated value to a datatable column when adding a new row in datatable 当源DataTable行具有DBNull.Value时,SqlBulkCopy进入表,默认列值失败 - SqlBulkCopy into table that Default column values fails when source DataTable row has DBNull.Value 向每个数据表添加新行时相关数据表出现问题 - Problem with releated datatable when adding new rows to each datatable 在批量复制之前将DBNull值插入DataTable列 - Inserting DBNull value to a DataTable column before bulk copy 在SQL Image列中插入DBNull时发生异常 - Exception when inserting DBNull in SQL Image column MySQL /实体框架-生成模型时发生错误“ RelationshipDetails中列“ FkColumn为DBNull”的值” - MySQL/Entity Framework - Error 'The value for column 'FkColumn in RelationshipDetails is DBNull' occurs when generating the model 向数据表添加行时出现奇怪的错误 - Strange error when adding row to datatable 具有dbnull异常的自动编号和数据表 - Autonumber and datatable with dbnull exception 向数据表添加新行 - Adding new row to a DataTable 尝试向数字添加逗号时出现DBNull错误 - DBNull error when attempting to add commas to numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM