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
Your Filters
Interested
Ignored
     
0 Shai Vashdi 1,588
1 OriginalGriff 528
2 Manas Bhardwaj 383
3 Damith Weerasinghe 330
4 Tadit Dash 315
0 Sergey Alexandrovich Kryukov 9,575
1 OriginalGriff 6,006
2 Peter Leow 4,500
3 Maciej Los 3,540
4 Abhinav S 3,513


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