如何将特定行从DataTable复制到另一行

本文关键字:一行 复制 DataTable | 更新日期: 2024-09-20 20:14:10

我想将数据表的一些行复制到另一行。我试过这个代码:

 DataTable Result = new DataTable();
    for(int i = 5; i < PageSize && i < TransactionDataTable.Rows.Count ; i++)
    {
        DataRow dr = (DataRow)TransactionDataTable.Rows[i];
        Result.ImportRow(dr);
    }
    string MobileNumber = TransactionDataTable.Rows[0]["MobileRegistration_MobileNumber"].ToString();
    string MobileNumber2 = Result.Rows[0]["MobileRegistration_MobileNumber"].ToString();
TransactionDataTable is a dataTable with more than 1000 rows.

在上面的代码中,MobileNumber有适当的值,但MobileNumber2没有。我在最后一行得到了这个错误(在分配MobileNumber2值时):

Additional information: Column 'MobileRegistration_MobileNumber' does not belong to table .

结果数据表中的行似乎没有正确复制。

这个代码怎么了?

我尝试了Result.Rows.Add(dr);而不是Result.ImportRow(dr);但有以下信息的异常抛出:

This row already belongs to another table.

谢谢你的帮助。。。

如何将特定行从DataTable复制到另一行

您正在制作没有任何列的新datatable Result。因此,请确保从要复制的表中提取所有列。在您的情况下,可以克隆TransactionDataTable,然后导入该行。

更新后的副本实现方式如下:

    DataTable Result = TransactionDataTable.Clone();
    for(int i = 5; i < PageSize && i < TransactionDataTable.Rows.Count ; i++)
    {
        DataRow dr = (DataRow)TransactionDataTable.Rows[i];
        Result.ImportRow(dr);
    }
    string MobileNumber = TransactionDataTable.Rows[0]["MobileRegistration_MobileNumber"].ToString();
    string MobileNumber2 = Result.Rows[0]["MobileRegistration_MobileNumber"].ToString();