简体   繁体   English

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

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

I want to copy some rows of data table, to another one. 我想将数据表的某些行复制到另一行。 I tried this code : 我尝试了这段代码:

 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.

in above code, MobileNumber has proper vallue, but MobileNumber2 dosent have. 在上面的代码中,MobileNumber具有适当的值,但MobileNumber2具有。 I got this error in last line ( in assigning MobileNumber2 value) : 我在最后一行(分配MobileNumber2值)中遇到了此错误:

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

It seems that the rows didnt copy properly, in Result dataTable. 似乎行未正确复制到Result dataTable中。

whats the wrong with this code? 此代码有什么问题?

and I tried Result.Rows.Add(dr); 我尝试了Result.Rows.Add(dr); instead of Result.ImportRow(dr); 而不是Result.ImportRow(dr); but an exception throw with this information: 但是此信息引发异常:

This row already belongs to another table.

Thanks for any helping... 感谢您的帮助...

You are making new datatable Result without any column. 您正在创建没有任何列的新数据表datatable Result So, make sure you are bringing all columns from the table which you are going to copy. 因此,请确保从表中复制要复制的所有列。 In your case, you can clone the TransactionDataTable and then import the row. 对于您的情况,可以克隆TransactionDataTable ,然后导入该行。

The updated copy implementation will be like this : 更新的副本实现将如下所示:

    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