设置列值时出现StrongTypingException

时间:2013-03-12 15:04:50

标签: c# .net strongly-typed-dataset

有人可以告诉我为什么在为强类型DataTable中的一个列分配值时会出现StrongTypingException吗? (我明白为什么如果我用DBNull值读取列,我会得到它)

在下面的示例中,我尝试将一个DataTable中的值分配给另一个DataTable(示例中的所有列都是 Int32 类型)。我可以为'newOrderRow.items'列分配一个值,但是当我对'newOrderRow.debcode'列执行相同操作时,会抛出异常!为什么呢?!

到目前为止我尝试过的一些事情(没有任何运气):
- 分配硬编码值而不是'calclineRow.debcode' - 在分配另一个值之前调用newOrderRow.SetdebcodeNull() - 将'orderrows'表中'debcode'列的DefaultValue属性从DBNull更改为-1并且它STILL抛出异常并说它是DBNull !!!

myDataSet.orderrowsRow newOrderRow;

foreach (MyDataSet.calclinesRow calclineRow in myDataSet.calclines)
{
    newOrderRow = myDataSet.orderrows.NeworderrowsRow();  //Create new 'orderrows' row

    //Assign values from one DataTable to another
    if (!calclineRow.IsitemsNull())
        newOrderRow.items = calclineRow.items;  //calclineRow.items == 1. Assignment successful
    if (!calclineRow.IsdebcodeNull()) 
        newOrderRow.debcode = calclineRow.debcode; //calclineRow.debcode == 556. Assignment raises System.Data.StrongTypingException ! (See message below)


    myDataSet.orderrows.AddorderrowsRow(newOrderRow);
}

/*Exception Message:
=====================

System.Data.StrongTypingException: The value for column 'debcode' in table 'orderrows' is DBNull. 
---> System.InvalidCastException: Specified cast is not valid. 
at MyProject.MyDataSet.orderrowsRow.get_debcode() in Q:\MyProjFolder\DataSets\MyDataSet.Designer.cs:line 21680
*/

3 个答案:

答案 0 :(得分:4)

如果nullable属性为null,则必须使用自动生成的SetNull方法:

if (!calclineRow.IsitemsNull())
    newOrderRow.items = calclineRow.items;  
else
    newOrderRow.SetitemsNull();

if (!calclineRow.IsdebcodeNull()) 
    newOrderRow.debcode = calclineRow.debcode; 
else
    newOrderRow.SetdebcodeNull();

您还必须在循环中向新表DataRow添加广告,因为NeworderrowsRow不会自动执行此操作。

myDataSet.orderrows.AddNeworderrowsRow(newOrderRow);

发生异常的行(MyDataSet.Designer.cs:行21680)表明它是从DataSet的自动生成的方法中引发的,该方法读取此属性。由于您没有使用SetdebcodeNull,因此它不知道它为空并在尝试读取它时抛出StrongTypingException

答案 1 :(得分:0)

你可以试试这个:

if (!calclineRow.IsdebcodeNull()) 
    newOrderRow["debcode"] = calclineRow.debcode;

虽然我承认它没有多大意义,但似乎为newOrderRow.debcode调用Set会调用Get,如上所述会抛出异常,如果基础属性是DbNull。

答案 2 :(得分:0)

解决。对不起,我的坏。

我忘记了我正在使用DataTable上的OnColumnChanging事件处理程序中的'debcode'列进行操作。当我禁用它时它一切正常。

非常感谢!

相关问题