DataRowCollection RemoveAt doesn't work in certain circumstances

  • Thread starter Thread starter Paul Guides
  • Start date Start date
P

Paul Guides

Hi all,

I am using the following code to remove rows from a table.

Only rows which match a certain value are removed.

The code works in one form very reliable and fails in another.

The only difference between the two usages seems to be, that
in the one Form a typed dataset is used and an untyped one
in the other.

DataTable tab = ds.Tables[ tabName ];
DataColumn col = tab.Columns[ colName ];
DataRowCollection rc = tab.Rows;
for( int idx = 0; idx < rc.Count; idx++ ) {
DataRow row = rc[ idx ];
if( row.RowState == DataRowState.Deleted ) {
if( row[ col, DataRowVersion.Original ].ToString()
== id ) {
rc.RemoveAt( idx );
idx--;
}
} else {
if( row[ col ].ToString() == id ) {
rc.RemoveAt( idx );
idx--;
}
}
}


The failure appears in the first RemoveAt statement:
The row is just not removed. No exception is thrown,
nothing happens, but the row just stays there. The
code, as shown above, then produces an endless loop.

As said above, in another Form this code works.

Karl
 
Hi Paul,

You are looping until idx < rc.Count while count changes when row is
removed...
It would be better to loop:
for (int idx=rc.Count-1; idx>=0; idx--)
and just remove the rows you wan't without touching idx variable.
 
Hi Karl

It seems like it is not a matter of typed or un typed dataset. I
have simulated your situation using un typed dataset and the deletion worked
ok “ here included in my replay the example that I created with un typed
dataset and it works ok “ so I think you should direct your search to some
other point to find the source of your problem. . I hope this would help.





myset = new DataSet();

mytable = new DataTable("trial");

mycolumn = new DataColumn("col1" ,
Type.GetType("System.Decimal"));

mytable.Columns.Add(mycolumn);

DataRow myrow = mytable.NewRow();

myrow["col1"]= 11.1;

mytable.Rows.Add(myrow);

mytable.Rows.Add(new object[]{12.2});

mytable.Rows.Add(new object[]{14.7});

myset.Tables.Add(mytable);

DataRowCollection r = mytable.Rows;

/*foreach (DataRow k in r)

{

if (k.RowState ==
System.Data.DataRowState.Deleted){}

else

{

mytable.Rows.Remove(k);

}

}*/

for( int idx = 0; idx < r.Count; idx++ )

{

DataRow row = mytable.Rows[ idx ];

if( row.RowState == DataRowState.Deleted )

{

if( row[ mycolumn,
DataRowVersion.Original ].ToString()== "12.2" )

{

r.RemoveAt( idx );

idx--;

}

}

else

{

if( row[ mycolumn].ToString() == "12.2" )

{

r.RemoveAt( idx );

idx--;

}

}

}



myset.WriteXml("c:\\temp.xml ",
System.Data.XmlWriteMode.DiffGram);

}

}
 
Back
Top