简体   繁体   中英

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. I got this error in last line ( in assigning MobileNumber2 value) :

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

It seems that the rows didnt copy properly, in Result dataTable.

whats the wrong with this code?

and I tried Result.Rows.Add(dr); instead of 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. 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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