Update and Delete Rows in a DataTable

One guy asked me a question, he was having problems in updating and deleting rows when looping through a DataTable rows.
 
A typical scenario is, say you have to loop through a DataTable rows and do some calculations on the rows and delete some rows depending on the condition. For example, deleting rows with Name = Mahesh.
 
If you do like in the following code, you will get an error on AcceptChanges method and the reason is deleting rows inside the loop means affecting the indexing.
  1. ' Loop though the table  
  2.  For Each dr As DataRow In ds.Tables(0).Rows  
  3.       If (dr("Name") = "Mahesh" Then  
  4.             dr.Delete()  
  5.       End If  
  6. ds.Tables(0).AcceptChanges()  
  7. Next  
However, if you mark the rows as delete using Delete method and accept changes on the DataTable outside the loop, you should be good to go. See the following code:
  1. ' Loop though the table  
  2.  For Each dr As DataRow In ds.Tables(0).Rows  
  3.       If (dr("Name") = "Mahesh" Then  
  4.             dr.Delete()  
  5.       End If  
  6. Next  
  7. ds.Tables(0).AcceptChanges()


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.