0

So, I have a DataRelation as is shown below:

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

where dsPubs is dsPubs = new DataSet() and that DataSet has two tables which Both have a data relation. Then; I am iterating over the parents to get the childs, just to get some task done as is shown next:

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

    }
}

and what I want to do is to remove all the child and the parent from an a specified value which is passed through a function(i.e).

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"   
                       }

                    }
                }

}

I tried to get it done by using rowTitle.Delete() and rowAuthor.Delete() method but it seemed to not be working, because I think it removes the whole table, and a the time The foreach wanted to continue to grab another value from the table "Consecuente" it crashed. Thank you a lot!!

  • Did you read the [DataRow.Delete](https://msdn.microsoft.com/en-us/library/system.data.datarow.delete%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) remarks? You cannot use this method in a foreach loop. See also [this](http://stackoverflow.com/questions/2341580/safely-removing-datarow-in-foreach) message. – Jeroen Heier Mar 17 '16 at 20:06
  • true you can't call .Delete() in a foreach loop but you can add the rows you want to delete to a separate list and then call delete afterwards. I'll post an answer... – Neil Hibbert Mar 17 '16 at 20:18

1 Answers1

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();
}
Neil Hibbert
  • 852
  • 5
  • 10