[英]Adding a Row to a DataTable question
大家問候
在下面的代碼中,如果電子郵件地址不匹配,我嘗試將現有DataTable(dtResult)中的行添加到新DataTable(dtCopyResult)中。 因此,我想我對ADO.NET的了解還不夠,因為每當我嘗試運行下面的代碼時,我都會得到“此行已屬於另一個表”。 請讓我知道如何解決此問題。
非常感謝
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
}
}
}
}
如錯誤消息所示,DataRow屬於特定的DataTable。 您不能只接受它並將其添加到另一個。 您可以做的就是
創建一個新的 DataRow並用舊DataRow中的值填充它,或
使用DataTable.ImportRow方法:
dtCopyResult.ImportRow(dtResult.Rows[i]);
您可以使用ImportRow
函數,完整的示例在這里http://support.microsoft.com/kb/308909
我注意到的一件事是,新行將被添加多次。 電子郵件集合中的每個項目一次。 您需要保留一個已經添加的項目的本地列表,或者遍歷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());
}
這意味着添加的行屬於“ dtResult”,而DataRow是表示數據的“對象”。 不是數據本身。 所以在這種情況下,您嘗試添加屬於另一個表的DataRow對象,這將出錯。
另一種方法是將所有內容復制到dtCopy並在條件不匹配時將其刪除。 數組主要用於存儲各種類型的對象。 在這種情況下,如果您只存儲電子郵件,則應使用
List<string> emails = new List<string>();
emails.Add("test@example.com");
枚舉刪除數據的行
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);
使用“刪除”的原因是,如果您在行中循環並同時刪除它,則意味着您更改了枚舉,這將導致錯誤。 當您拉出其循環時,becus .Net不高興。
嘗試更換
dtCopyResult.Rows.Add(dtResult.Rows[i]);
與
DataRow rowToBeCopied = dtCopyResult.NewRow();
//Copy the row values..
rowToBeCopied.X = dtResult.Rows[i].X;
//Copy the remaining row values
dtCopyResult.Rows.Add(rowToBeCopied);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.