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

How to copy specific rows from DataTable to another one

我想将一些数据行 table 复制到另一行。我试过这段代码:

 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 Result。因此,请确保将要复制的 table 中的所有列都带进来。 在您的情况下,您可以克隆 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();