2016-03-17 40 views
0

所以,我有一個DataRelation如下面所示:如何刪除DataSet中的所有子行和父項?

Oraciones1 = new DataRelation("Antecedentes", 
     dsPubs.Tables["Consecuente"].Columns["Id"], 
     dsPubs.Tables["Antecedentes"].Columns["Id"]); 
     dsPubs.Relations.Add(Oraciones1); 

dsPubs哪裏是dsPubs = new DataSet()和該數據集具有兩個表,其兩者都有的數據關聯。然後;我遍歷父母獲得孩子的,只是爲了得到一些任務完成如圖所示:

foreach (DataRow rowAuthor in dsPubs.Tables["Consecuente"].Rows) {    
    foreach (DataRow rowTitle in rowAuthor.GetChildRows(Oraciones1)) { 

    } 
} 

和我想要做的是從一個指定的值刪除所有的孩子和家長哪些通過一個函數(即)。

public void function(string value){ 
    foreach (DataRow rowAuthor in dsPubs.Tables["Consecuente"].Rows){    
      foreach (DataRow rowTitle in rowAuthor.GetChildRows(Oraciones1){ 

         if(value==rowTitle["id_d"].ToString()){ 
          //remove all the child and the parent from the specified variable "value" 
         } 

        } 
       } 

} 

我試圖把它用rowTitle.Delete() and rowAuthor.Delete() method完成,但它似乎沒有工作,因爲我覺得它刪除整個表,和時間在foreach想繼續從表"Consecuente"去搶另一個的值它墜毀。 非常感謝!

+0

你看了[DataRow.Delete(https://msdn.microsoft.com/en-us/library/system.data.datarow.delete%28v=vs.110%29.aspx? f = 255&MSPPError = -2147217396)備註?你不能在foreach循環中使用這個方法。另見[this](http://stackoverflow.com/questions/2341580/safely-removing-datarow-in-foreach)消息。 –

+0

true你不能在foreach循環中調用.Delete(),但可以將要刪除的行添加到單獨的列表中,然後再調用delete。我會發佈一個答案... –

回答

0
var innerRows = new List<DataRow>(); 
var outerRows = new List<DataRow>(); 

foreach (DataRow rowAuthor in dsPubs.Tables["Consecuente"].Rows) 
{ 
    foreach (DataRow rowTitle in rowAuthor.GetChildRows(Oraciones1)) 
    { 
     if (value == rowTitle["id_d"].ToString()) 
     { 
     //remove all the child and the parent from the specified variable "value" 
     innerRows.Add(rowTitle); 
     outerRows.Add(rowAuthor); 

     } 

    } 
} 

foreach(DataRow row in innerRows) 
{ 
    row.Delete(); 
} 

foreach (DataRow row in outerRows) 
{ 
    row.Delete(); 
} 
相關問題