2010-11-16 84 views
1

問候everyone-添加行到DataTable問題

在我的代碼下面我試圖從現有的數據表(dtResult)添加一行到一個新的DataTable(dtCopyResult)如果電子郵件地址不匹配。所以我猜我對ADO.NET的瞭解不夠全面,因爲每當我嘗試運行我的下面的代碼時,我都會得到一個「This Row already already belong to another table」。請讓我知道我該如何解決這個..

非常感謝

if (checkBox1.Checked) 
        { 

         for (int i = dtResult.Rows.Count - 1; i >= 0; i--) //dtResult is a DataTable 
         { 
          foreach (object email in emails) //emails is an ArrayList of email addresses 
          { 
           if (email.ToString().ToUpper() != dtResult.Rows[i][3].ToString().ToUpper()) 
           { 
            dtCopyResult.Rows.Add(dtResult.Rows[i]); //dtCopyResult is a new blank DataTable that I'm trying to add rows to 
           } 
          } 

         } 

        } 
+0

嘗試使用CopyResult.Rows.Add(new dtResult.Rows [i]);只是猜測 – Gage 2010-11-16 16:54:18

回答

6

隨着錯誤消息告訴您,一個DataRow屬於特定的數據表;你不能把它拿到另一個。你能做的要麼是

  • 創建的DataRow,並從舊的DataRow或值

  • 填充它使用DataTable.ImportRow方法:

    dtCopyResult.ImportRow(dtResult.Rows[i]); 
    
+0

+1希望我可以記住ImportRow :-)絕對要走的路 – InSane 2010-11-16 17:01:35

+0

+1爲了向我展示ImportRow,不知道它存在。 – Gage 2010-11-16 17:03:16

+0

嗨Heinzi-在使用ImportRow時,我會得到整行嗎?我想問的原因是我的foreach循環完成後,我回去搜索一個特定的列,以便我可以檢查該行內的值,並且得到「列不存在」。思考? – Josh 2010-11-16 17:47:31

0

這意味着添加行屬於「dtResult」,DataRow是表示數據的「對象」。不是數據本身。所以在這種情況下,你嘗試添加屬於另一個表的錯誤的DataRow對象。

另一種方法是將所有內容複製到dtCopy並在條件不匹配時將其刪除。數組主要用來存儲各種類型的對象。在這種情況下,如果妳要去店裏只有電子郵件ü應使用

List<string> emails = new List<string>(); 
emails.Add("[email protected]"); 

枚舉行的delete一個數據

List<DataRow> removing = new List<DataRow>(); 
foreach(var row in table.AsEnumerable()) // or table.Rows 
if(...condition)removing.Add(row); 

foreach(var row in removing)table.Rows.Remove(row); 

使用「刪除」的原因是如果u遍歷行和刪除它同時,意味着你改變了會導致錯誤的枚舉。因爲.net在你抽出一些東西時會不高興。

0

嘗試

DataRow rowToBeCopied = dtCopyResult.NewRow(); 
//Copy the row values.. 
rowToBeCopied.X = dtResult.Rows[i].X; 
//Copy the remaining row values 
dtCopyResult.Rows.Add(rowToBeCopied); 
1

一個我注意到的是,新的行會得到多次添加;一次爲電子郵件收藏中的每個項目。 您需要保留已添加的項目的本地列表,或者通過dtCopyResult循環以確保您尚未添加電子郵件。

List<string> alreadyAdded = new List<string>(); 

if (email.ToString().ToUpper() != dtResult.Rows[i][0].ToString().ToUpper() 
    && !alreadyAdded.Contains(email.ToString())) 
{ 
    dtCopyResult.ImportRow(_dt1.Rows[i]); 
    alreadyAdded.Add(email.ToString()); 
}