none
dataset row delete problem RRS feed

  • Question

  • im trying to delete a few rows using a foreach statment but after the first deleted row it throws a error here is the code

    foreach(dataset.Table1Row row in ds.Table1.Rows)

    {

    if (row.Type == i)

    row.Delete();

    }

    the error has to do with the modification of the dataset in a loop

    the only other thing I can think of is to save the row index into a array then loop using a for statment and delete that way but cant figure out how to get the row index number

    thanks

    j

     

    Friday, August 18, 2006 4:29 AM

All replies

  • well yes, you are modifying the object whilst iterating through it - it doesnt work like this.

    you may wish to say, copy over the datatable to another datatable:

     

    DataTable theCopiedDT = dataSet.Tables[0];

     

    then go through each element of the copied datatable and remove the row FROM the dataset.

     

    something like

     

    DataTable theCopiedDT = dataSet.Tables[0]

     

    foreach (DataRow currentRow in dataSet.Tables[0].Rows)

    {

       theCopiedDT.Rows.Delete(currentRow);

    }

     

    dataSet.Tables.Clear();

    dataSet.Tables.Add(theCopiedDT);

     

    IF you are wanting to remove all datarows, just clear out the rows:

     

    dataSet.Tables[0].Rows.Clear();

     

    or remove the table:

     

    dataSet.Tables.Remove("yourTableName");

     

    does this help? is this what you are after?

    Friday, August 18, 2006 4:38 AM
  • The standard way to do this is using a down-counting for loop:

    for(int i = ds.Table1.Rows.Count - 1; i >= 0; i--)
    {
      dataset.Table1Row row = (dataset.Table1Row)ds.Table1.RowsIdea;
      if(row.Type == x)
        row.Delete();
    }


    The counting backwards is important, because if you count upwards and delete a row, then all the remaining rows shift up one, so the indexes change and you could skip rows.
    Friday, August 18, 2006 12:32 PM
  • the counting backwords works great, thanks for the help
    Friday, August 18, 2006 2:13 PM
  • Just ran into this myself. 

    To expand on what's happening here, row.Delete() applied to a row whose state is unchanged/modified, will mark the row for deletion and the Count is unchanged.

    However, if row.Delete() is applied to a row whose state is Added, then there's no longer any reaon to keep the row in the collection (never existed in the backend data store) and the row is really deleted from the collection and the Count is decremented.

    Counting down gets around this problem.  You've already visited the rows whose index changes when the row is removed.

    Toby

    Friday, January 5, 2007 6:18 PM