Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
C#
if (NSFwithExtOrSerFound)
                     {
                         int count = 0;
                       foreach (DataRow recRow in dtRec.Rows)
                         {
                             if (recRow[0].ToString() == "Contact Vibration Specialist")
                             {
                                 count++;
                             }
                         }

                       foreach (DataRow recRow in dtRec.Rows)
                       {
                           if (recRow[0].ToString() == "Contact Vibration Specialist")
                           {
                               count--;
                               if (count > 0)
                               {
                                   recRow[0] = string.Empty;
                                   recRow.Delete();
                               }
                           }
                       }
                     }

I am deleting a specific row in the datatable but at
C#
recRow.Delete();
i am getting an error like [System.InvalidOperationException] = {"Collection was modified; enumeration operation might not execute."}
Posted
Updated 20-Apr-23 20:51pm
v2

Hi

One rule with FOREACH loop is that, you cannot modify the loop collection. So try using FOR loop.

try this.

C#
for(int i=0; i < dtRec.Rows.Count; i++)
{
   DataRow recRow = dtRec.Rows[i];
   if (recRow[0].ToString() == "Contact Vibration Specialist")
   {
       count--;
       if (count > 0)
       {
           recRow[0] = string.Empty;
           recRow.Delete();
           dtRec.AcceptChanges();
       }
   }
}


hope it helps.
 
Share this answer
 
Comments
chandra sekhar 19-Aug-14 5:24am    
That worked like a charm :)
Karthik Harve 19-Aug-14 5:25am    
Good. Happy Coding :)
You will need to change the delete statement in the following format
C#
dt.Rows.Remove(dr);
dt.AcceptChanges();


where dt is the data table from where you would like to delete the row and dr is the particular row which needs to be deleted.
 
Share this answer
 
i chose the last solution.solution 2.

but after the table name there is no acceptchanges() option.
 
Share this answer
 
Comments
CHill60 1-Feb-21 8:53am    
This is not a solution to the question. If you have a question of your own then use the red "Ask a Question" link at the top of this page. You will need to include your code. If AcceptChanges is not showing under auto-complete when you enter the period (.) then you may have a compiler error elsewhere in your code - fix that first.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900