2012-04-16 41 views
0

我想插入數據行過濾器值到datatable,但它返回以下錯誤「此行已屬於另一個表」。請幫我解決這個錯誤..datarow過濾器值到數據表

這是我的部分代碼:

for (int j = 0; j < ListBox1.Items.Count; j++) 
       { 
        DataView DV = new DataView(); 
        DV = DS1.DefaultView; 
        DV.RowFilter = "fldemployee='" + ListBox1.Items[j].Text + "' and fldassigndate = '04-07-2012'"; 
        if (DV.Count > 0) 
        { 
         DataTable table = DV.ToTable("sp_getallattendancesetup"); 
         DataRow row = table.Rows[0]; 
         DT.Rows.Add(row); 

        } 

       } 

       GridView1.DataSource = DT; 
       GridView1.DataBind(); 
+0

http://stackoverflow.com/questions/722052/this-row-already-belongs-to-another-table-error-when-trying-to-add-rows – Rawling 2012-04-16 09:49:18

回答

0

您可以使用從MSDN ImportRow

DT.Rows.ImportRow(row); 

信息:調用NEWROW添加一行到表使用 現有表架構,但使用該行的默認值,並且 將DataRowState設置爲已添加。調用ImportRow將保留現有的DataRowState以及該行中的其他值。如果作爲參數傳遞的 DataRow處於分離狀態,則會忽略 ,並且不會引發異常。

新行將被添加到數據表的末尾。

如果新行違反了約束條件,它將不會被添加到數據表 表中。

您可以使用DataTable.Rows.Find和 DataTable.Rows.IndexOf獲取新行的索引。有關更多 信息,請參閱DataRowCollection和行。

參考here