C# 将单行从一个数据表复制到另一个数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10330173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:25:27  来源:igfitidea点击:

copy a single row from one datatable to other

c#asp.netado.netdatatabledatarow

提问by MaxRecursion

I have two datatables one has few rows other is empty. I am running a loop over first one to copy some of the rows to another table. I am getting error 'The row already belongs to another table'.

我有两个数据表,一个有几行,另一个是空的。我在第一个上运行循环以将一些行复制到另一个表。我收到错误“该行已属于另一个表”。

Is there any way to copy DataRows one by one to other DataTable.

有什么办法可以将DataRows一一复制到其他DataTable。

thanks in advance

提前致谢

采纳答案by Nikhil Agrawal

Use

newtable.ImportRow(oldtable.Rows[i]) 

where iis the desired row number.

哪里i是所需的行号。

as explained in http://support.microsoft.com/kb/308909/en-us

http://support.microsoft.com/kb/308909/en-us 中所述

回答by blindmeis

copy the ItemArray, of course just works when the columns are the same

复制 ItemArray,当然只在列相同时才有效

var dtCopyTo = new DataTable();
foreach(var rowCopyFrom in dtCopyFrom.Rows)
{
    var updatedDataRow = dtCopyTo.NewRow();
    updatedDataRow.ItemArray = rowCopyFrom.ItemArray;
    dtCopyTo.AddRow(updatedDataRow);
}

ps: code is typed without ide so check syntax pls

ps:代码是在没有ide的情况下输入的,所以请检查语法