繁体   English   中英

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

[英]How to copy specific rows from DataTable to another one

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

 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.

感谢您的帮助...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM