在操作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