c# - 将数据行从一个数据表插入到特定索引

标签 c# .net datatable datarow

<分区>

我正在从我的数据库中检索 DataTables,我需要将一个 DataTable 中的特定行插入到另一个 DataTable 的确定索引中.

基本上我想说的是,DataTable dt1 的行 [0] 插入到索引 4 处的 DataTable dt2。

这是从两个不同的数据库调用中获得的两个不同的表。有办法做到这一点吗?

如有任何帮助,我们将不胜感激。

[编辑] 抱歉,这是我所做的

DataTable dt1 = populateTable();
DataTable targetTable = populateTargetTable();
DataRow dr;
dr = dt1.NewRow();
dr = targetTable.Rows[0];

int index=0;
DataRow temp;
for (int i = 0; i < dt1.Rows.Count; i++)
{
    temp = dt1.Rows[i];
    if (rowFitsCondition(temp)){
        index = i;
    }
}
dt1.Rows.InsertAt(dr, index);

并且 InsertAt() 调用失败,并给我 This row already belongs to another table 错误。

最佳答案

尝试使用克隆

dr= dt1.NewRow();
dr.ItemArray = targetTable.Rows[0].ItemArray.Clone() as object[]; 
dt1.Rows.InsertAt(dr, index);

关于c# - 将数据行从一个数据表插入到特定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428107/

相关文章:

c# - 生成逗号分隔值

c# - FMOD 无缝循环和序列播放

javascript - 如何将选定的下拉列表值附加到 aspx 页面本身的超链接查询字符串

c# - 如何安装网页 v1.0

.net - 存在哪些 CLR/.NET 字节码工具?

c# - 使用 LINQ 查询 DataColumnCollection

datatable - 使用 Firestore 和 Flutter 填充 DataTable(使用 StreamBuilder)

c# - 脚手架项目的包恢复失败问题

c# - 控制台应用程序提示输入

mysql - 稍微更改了 MYSQL 数据库表,需要此查询像以前一样工作