设置列值时的StrongTypingException
本文关键字:StrongTypingException 设置 | 更新日期: 2023-09-27 18:03:26
谁能告诉我为什么我得到一个StrongTypingException时,在一个强类型数据表的列分配一个值?(我明白为什么我得到它,如果我读与DBNull值列)
在下面的示例中,我试图将一个数据表的值分配给另一个(示例中的所有列都是类型Int32)。我可以给'newOrderRow '赋值。items'列,但当我对'newOrderRow.debcode'列做同样的事情时,抛出异常!为什么? !
到目前为止我尝试过的一些事情(没有任何运气):
-分配硬编码值而不是'calclineRow.debcode'
-在分配另一个值之前调用newOrderRow.SetdebcodeNull()
-在'orderrows'表中'debcode'列的DefaultValue属性从DBNull更改为-1和它仍然抛出异常并说它是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
*/
如果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:line 21680)表明它是从读取此属性的DataSet
的自动生成方法引发的。因为你没有使用SetdebcodeNull
,它不知道它是空的,并抛出StrongTypingException
当它试图读取它。
你可以试试:
if (!calclineRow.IsdebcodeNull())
newOrderRow["debcode"] = calclineRow.debcode;
虽然我承认它没有多大意义,但似乎为newOrderRow.debcode调用Set
具有调用Get
的效果,如所述,如果底层属性是DbNull,则会抛出异常。
已解决。对不起,我错了。
我忘记了我正在做的事情与'debcode'列在OnColumnChanging事件处理程序上我的数据表。当我禁用它时,它就能正常工作了。
谢谢!