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

时间:2015-03-03 05:29:29

标签: c# winforms datatable

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

 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 dataTable中,行似乎没有正确复制。

这段代码出了什么问题?

我尝试Result.Rows.Add(dr);代替Result.ImportRow(dr); 但是有这个信息的例外情况:

This row already belongs to another table.

感谢任何帮助...

1 个答案:

答案 0 :(得分:1)

您正在创建没有任何列的新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();