Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.<br />
<br />

When i'm deleting single row using checkbox on button click then it is working fine but when i'm deleting multiple row then it is throwing exception.

can anyone help me out?

here is my code-

C#
foreach (GridViewRow row in GridView1.Rows)
        {

            CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
            if (chk.Checked)
            {

                int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                SqlConnection sqlconn = new SqlConnection("server=.\\sqlexpress;database=practice;integrated security=true");
                SqlCommand sqlcomm = new SqlCommand("delete from prac where id='"+id+"'", sqlconn);
                sqlconn.Open();
                sqlcomm.ExecuteNonQuery();
                sqlconn.Close();
                Label1.Text = "Record Deleted";
                Binddata();
            
            }
        
        
        }
Posted
Updated 3-Jan-13 21:03pm
v3

1 solution

Your issue is that you call Binddata() on every iteration of a row.
Move the Binddata() call out of the foreach completely. Don't rebind your data until you are done processing.
C#
foreach (GridViewRow row in GridView1.Rows)
{
   CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
   if (chk.Checked)
   {
      int id = Convert.ToInt32("",GridView1.DataKeys[row.RowIndex].Value);
      SqlConnection sqlconn = new SqlConnection("server=.\\sqlexpress;database=practice;integrated security=true");
      SqlCommand sqlcomm = new SqlCommand("delete from prac where id='"+id+"'", sqlconn);
      sqlconn.Open();
      sqlcomm.ExecuteNonQuery();
      sqlconn.Close();
      Label1.Text = "Record Deleted";           
   }    
}
Binddata();
 
Share this answer
 
v3
Comments
Surendra0x2 4-Jan-13 3:01am    
Thanks a ton Marcus u solved my problem :)
fjdiewornncalwe 4-Jan-13 4:24am    
You're welcome.

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