Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# Gridview
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
 

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-
 
 
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 3-Jan-13 6:47am
Edited 3-Jan-13 21:03pm
v3

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
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();
  Permalink  
v3
Comments
Surendra0x2 at 4-Jan-13 3:01am
   
Thanks a ton Marcus u solved my problem :)
Marcus Kramer at 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)

  Print Answers RSS
0 OriginalGriff 6,656
1 Sergey Alexandrovich Kryukov 6,400
2 CPallini 5,240
3 George Jonsson 3,584
4 Gihan Liyanage 2,625


Advertise | Privacy | Mobile
Web03 | 2.8.140921.1 | Last Updated 4 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100