【问题标题】:DataRow value missing after InsertAt() methodInsertAt() 方法后缺少 DataRow 值
【发布时间】:2014-02-27 00:35:08
【问题描述】:
我有一个示例代码,如下所示。
DataRow dr = DTSource.Rows[rowIndex]; //getting specified index row
DTSource.Rows.RemoveAt(rowIndex); // deleting specified row
DTSource.Rows.InsertAt(dr, rowIndex - 1); // adding the row placed just above of the deleted row
这里,在将特定行插入到指定索引后,数据表在最近插入的地方显示了一个空行。如何添加包含数据的行而不是这个空行?
【问题讨论】:
标签:
c#
asp.net
datatable
datarow
【解决方案1】:
根据 Mnieto 和 Tim Schmelter 的回答,我已经像这样更改了我的代码。
DataRow dr = DTSource.NewRow();
for (int i = 0; i < DTSource.Columns.Count; i++)
dr[i] = DTSource.Rows[rowIndex][i];
现在它对我有用。
【解决方案2】:
dr 被删除。那是因为数据表显示一个空行。让我们一步一步看:
DataRow dr = DTSource.Rows[rowIndex];
你在 dr 变量中保存一行
DTSource.Rows.RemoveAt(rowIndex);
您删除了该行。 dr 变量现在指向已删除的行。
DTSource.Rows.InsertAt(dr, rowIndex - 1);
您正在另一个位置插入已删除的行
如果你想移动一个行位置,你应该做一个数据行的深拷贝。
【解决方案3】:
看看RemoveAt的文档:
从集合中删除指定索引处的行。
删除一行后,该行中的所有数据都将丢失。 ...
所以你需要临时保存数据,例如使用row.ItemArray
DataRow row = DTSource.Rows[rowIndex]; //getting specified index row
var data = row.ItemArray; // all fields of that row
DTSource.Rows.RemoveAt(rowIndex); // removes row and it's data
row.ItemArray = data; // reassign data
DTSource.Rows.InsertAt(row, rowIndex - 1); // adding the row placed just above of