2010-11-16 87 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()); 
}