0

I am trying to delete selected rows from gridview in button click event but I am getting the below error:

Collection was modified; enumeration operation might not execute.

Code:

    protected void btnRemoveUser_Click(object sender, EventArgs e)
    {  
      DataTable yourDataTable = GetDataTable(Studentlist);     
      //CheckBox chkbx;
      foreach(GridViewRow oneRow in Studentlist.Rows)
      {
        CheckBox  chkbx = (CheckBox)oneRow.FindControl("ckbxID");
          foreach (DataRow rowDT in yourDataTable.Rows)  **//In this line throwing the exception**
          {
              if (chkbx.Checked == true)
              {
                  yourDataTable.Rows.Remove(rowDT);  
              }

          }  
      }     

      Studentlist.DataSource = yourDataTable;
      Studentlist.DataBind();

  }

Note: Studentlist is the gridview ID.

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
user1133737
  • 113
  • 5
  • 22
  • Dnyanesh said : "You can not remove item from collection while performing foreach on it" that's true,so try to declare another datatable "DataTable newDataTable = yourDataTable;" and remove the rows from newDataTable and finally pass it to datasource – Nima Derakhshanjan Nov 09 '14 at 07:57

1 Answers1

0

You can not remove item from collection while performing foreach on it for details visit this.

For now you can use easy technique to delete items.

for(int i = 0; i< yourDataTable.Rows.Count; i++)
  {
      if (chkbx.Checked == true)
      {
          yourDataTable.Rows.RemoveAt(i);
      }
  }
Community
  • 1
  • 1
Dnyanesh
  • 2,265
  • 3
  • 20
  • 17
  • I can't see there is `Length()` function in Datatable.Rows , so it should throw compilation error. – Arindam Nayak Nov 09 '14 at 06:37
  • My mistake count will work in this case. Edited answer – Dnyanesh Nov 09 '14 at 06:46
  • @Dnyanesh:Thanks, for ur reply. Using this technique rows are not deleting properly for ex. if I select 1 row its deleting 2 or 3 rows. – user1133737 Nov 09 '14 at 06:58
  • It is deleting 2 or 3 row is ambiguous. Select only first row in grid and delete it. Result will be it will either it will delete the 1 row or will give some exception try it. – Dnyanesh Nov 09 '14 at 07:06
  • If I select first row its deleting 3 rows and not throwing any exception. – user1133737 Nov 09 '14 at 07:23
  • I do not see any obvious error in code but as it is deleting 3 rows means chkbx is true for 3 times, and that is something going wrong is what I can think of. – Dnyanesh Nov 09 '14 at 07:41