Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# InsertAt()方法后缺少DataRow值_C#_Asp.net_Datatable_Datarow - Fatal编程技术网

C# InsertAt()方法后缺少DataRow值

C# InsertAt()方法后缺少DataRow值,c#,asp.net,datatable,datarow,C#,Asp.net,Datatable,Datarow,我有一个示例代码如下所示 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 在这里,将特定行插入到

我有一个示例代码如下所示

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

在这里,将特定行插入到指定索引后,数据表将在最近插入的位置显示一个空行。如何添加包含数据的行而不是空行?

dr被删除。这是因为数据表显示一个空行。让我们一步一步来看看:

DataRow dr = DTSource.Rows[rowIndex];
在dr变量中保存一行

DTSource.Rows.RemoveAt(rowIndex);
删除该行。dr变量现在指向已删除的行

DTSource.Rows.InsertAt(dr, rowIndex - 1);
您正在另一个位置插入已删除的行


如果要移动行位置,应进行数据行的深度复制。

查看以下文档:

从集合中删除指定索引处的行。 删除行时,该行中的所有数据都将丢失

因此,您需要临时保存数据,例如使用
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

根据Mnieto和Tim Schmelter的回答,我已经像这样修改了我的代码

 DataRow dr = DTSource.NewRow();
                for (int i = 0; i < DTSource.Columns.Count; i++)                    
                    dr[i] = DTSource.Rows[rowIndex][i];
DataRow dr=DTSource.NewRow();
for(int i=0;i
现在它对我起作用了