Click here to Skip to main content
12,451,703 members (65,252 online)
Rate this:
 
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
Updated 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 4-Jan-13 3:01am
   
Thanks a ton Marcus u solved my problem :)
Marcus Kramer 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
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160826.1 | Last Updated 4 Jan 2013
Copyright © CodeProject, 1999-2016
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