C#中DataRow中使用ItemArray和setValue无法赋值的问题

在操作DataRow的数据时,往往要给其中一列赋值。编程的时候发现用ItemArray直接赋值,或者用setValue,对应的DataRow中相应的列的值都没有变化。

            DataRow dr;//省略了给dr赋值或者引用等的步骤

            dr.ItemArray[4] = value;//该值为int型(虽然与问题无关)
            dr.ItemArray.SetValue(value, 4);

断点跟踪发现这条语句执行前后dr[0].ItemArray[4]的值都没有变化。

查阅资料发现要用DataRow.SetField<>(using System.Data)或者直接DataRow[][]来进行赋值

            DataRow dr;//省略了给dr赋值或者引用等的步骤

            dr.SetField<int>(4, value);
            dr[4] = value;

 

原因是ItemArray[]返回的并不是object的引用,而是值传递回来的(不知道这样说是否准确?)。

The reason this doesn't work is that ItemArray returns a copy of the values in the row, it doesn't return an object where you can set the values on the row. In order to change the value on a row, you will want to use the indexer on the row

如果用ItemArray赋值,必须对整列赋值。见msdn:

You can use this property to set or get values for this row through an array. If you use this property to set values, the array must have the same size and ordering as the column collection. Passing null in the ItemArray indicates that no value was specified.

参考网页:

https://www.gamedev.net/forums/topic/559116-assignment-to-datarowitemarray-not-taking-c/

https://bytes.com/topic/c-sharp/answers/230636-datarow-setvalue-don-t-work

https://stackoverflow.com/questions/22781235/adding-values-to-a-row-itemarray

https://docs.microsoft.com/en-us/dotnet/api/system.data.datarow.itemarray?view=netframework-4.7.2

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值