C# .NET - How to delete selected rows from gridview datatable in button click event

Asked By Rahul Khanna on 09-Nov-14 09:57 AM
Hi all,
I am trying to delete selected rows from gridview in button click event.My code is not deleting the correct row, if I select first row its deleting the 2nd row and If I select 2nd row its deleting the 3rd row and so on. 

Here is my 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");         
       for(int i = 0; i< yourDataTable.Rows.Count; i++)
         if (chkbx.Checked == true)
Studentlist.DataSource = yourDataTable; Studentlist.DataBind(); } Note: Studentlist is the gridview ID.
Here, my purpose is to delete the selected rows from gridview so any alternate solution is also appreciated.
Robbe Morris replied to Rahul Khanna on 09-Nov-14 10:54 AM
I don't see where you are checking the id of the checkbox control to be certain you are deleting the right row from the datatable.

This code would always delete the first row of the datatable for every selected checkbox.  I doubt if that is what you are after.
Gorav Handa replied to Rahul Khanna on 05-Jan-15 09:58 PM
Match gridview row with datatable row on the basis of common id field before removing a record else it would always remove first row.