c# - 设置列值时出现 StrongTypingException

标签 c# .net strongly-typed-dataset

任何人都可以告诉我为什么在为强类型数据表中的列分配值时会收到 StrongTypingException 吗? (我明白为什么如果我要读取具有 DBNull 值的列,我会得到它)

在下面的示例中,我尝试将一个 DataTable 中的值分配给另一个 DataTable(示例中的所有列均为 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
*/

最佳答案

如果可空属性为 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,因此它不知道它是 null,并在尝试读取它时抛出 StrongTypingException

关于c# - 设置列值时出现 StrongTypingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15364819/

相关文章:

c# - 将通用数据表转换为类型化数据表

c# - 为具有 COM 对象的类编写正确的 IDisposable 实现

.net - 文化变化带来的问题

c# - 强类型数据集不会填充,表映射问题? c#.net 2.0

.net - WebClient.DownloadFileAsync 无法引发异常

c# - 为什么 Int32.Equals(Int16) 返回 true,而 reverse 不返回?

c# - 使用强类型数据集在关系中插入行

c# - 如何将 C++/CLI 字符串转换为 const char*

c# - 如何提高通过声卡传输文件的比特率?

c# - VS 2010 调试 - 可视化工具在哪里