finding row to delete

Can someone please help with the following problem.

I am trying to locate a row in the datatable to delete but am not sure how to go about this. I have decided to use a for loop to iterate through the datatable until a match is found with the entered ID number. However, when the matching ID number is found, the code that I use to delete the found row doesnt seem to work. I get a thrown exception saying that the row at position (n)does not exist in the table and the datagrid on the form goes blank.

The code that I am using to try to delete the found row is shown below.

int RowCount = 0;

foreach(DataRow dr in mydataset.Tables[1].Rows)
{
RowCount ++;

if (txtStudID.Text == dr[0].ToString())
{ mydataset.Tables[1].Rows[RowCount].Delete();
mydataset.WriteXml("C://Student1.xml");
mydataset.WriteXmlSchema("C://Student1.xml");

}

} //end of for loop
mydataset.Tables[1].Rows[RowCount].AcceptChanges();
f2.dataGrid1.DataSource = mydataset;
return;

Any help will be very much appreciated.
[1150 byte] By [Markyjj] at [2007-11-19 23:31:56]
# 1 Re: finding row to delete
Here is a guess:

for (int RowCount = 0; RowCount<mydataset.Tables[1].Rows.Count; RowCount ++)
{
DataRow dr = mydataset.Tables[1].Rows[RowCount];
if (txtStudID.Text == dr[0].ToString())
{
dr.Delete();
mydataset.WriteXml("C://Student1.xml");
mydataset.WriteXmlSchema("C://Student1.xml");
dr.AcceptChanges();
break;
}
} //end of for loop
//f2.dataGrid1.DataSource = mydataset; //only nessecary if the DataSource was not already set!!!
return;

Two things I fixed:
1. You can't delete a Row while iterating using the foreach statement.
2. If no row to delete than the AcceptChanges row would fail.
jhammer at 2007-11-10 3:30:19 >