Thursday, March 14, 2013

DataRow.Delete Is Not Equal To DataRows.Remove() OR DataRows.RemoveAt()

DataRow.Delete() VS DataRows.Remove() or RemoveAt()

==============================================================
Important Namespaces: 
- System.Data.Sql
-System.Data.SqlClient
==============================================================
Facing an issue inside one of my projects, i was trying to iterate through the datatable datarows and while i was iterating i was removing datarows using a loop index which was going from 0 upto row count of datatable. But i was constantly facing an error. 

"collection was modified. Enumeration operation might not execute."

There i got the difference. I was using DataRows.Remove() or DataRows.Removeat(). Both function remove the datarow physically and committedly from the datatable which was being used in that loop meanwhile. Now important thing is that you cannot mantain the same count of the rows if you are inside the loop and you are using DataTable.rows.count for iteration condition. 

BUT 

Instead you should use the DataRow.Delete() function. Delete() function will not physically delete the row from datatable. It will mark the row to be deleted or update the rowstate as RowState.deleted. The change will not be committed until you call Datatable.acceptchanges() function. 

Now whatever you do with your datatable it will not commit your changes until you call Acceptchanges() function. 



Earn Money ! Affiliate Program
Open Directory Project at dmoz.org