2015-03-03 82 views
1

我想將一些數據表的行復制到另一個表中。我試過這段代碼:如何將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 . 

似乎didnt複製不當,結果DataTable中的行。

這段代碼有什麼問題?

,我試圖Result.Rows.Add(dr);而不是Result.ImportRow(dr); 但異常拋出這一信息:

This row already belongs to another table. 

感謝您的任何幫助......

回答

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(); 
相關問題