Click here to Skip to main content
15,922,427 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
When i updating row in gridview ,then this error is coming
Index was out of range. Must be non-negative and less than the size of the collection.


What I have tried:

{
              GridViewRow row = GridView1.Rows[e.RowIndex];
              int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[1]);
              string name = (row.FindControl("txtName") as TextBox).Text;
              string country = (row.FindControl("txtCountry") as TextBox).Text;
              string query = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId";
              string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
              using (SqlConnection con = new SqlConnection(constr))
              {
                  using (SqlCommand cmd = new SqlCommand(query))
                  {
                      cmd.Parameters.AddWithValue("@CustomerId", customerId);
                      cmd.Parameters.AddWithValue("@Name", name);
                      cmd.Parameters.AddWithValue("@Country", country);
                      cmd.Connection = con;
                      con.Open();
                      cmd.ExecuteNonQuery();
                      con.Close();
                  }
              }
              GridView1.EditIndex = -1;
              this.BindGrid();
          }
Posted
Updated 21-Nov-18 19:06pm

1 solution

Start with the debugger, and look at your indexes - most likely e.RowIndex is -1 as nothing is selected. if that's the case, you need to add code to specifically check for negative values as you will normally get at least one negative value on startup for some events.
 
Share this answer
 
Comments
akhter86 22-Nov-18 1:57am    
error coming on this line
int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
OriginalGriff 22-Nov-18 2:09am    
So you have two indexes: e.RowIndex and 0.
So use the debugger and look at the DataKeys collection. How many elements? What's the value of e.RowIndex? Is there an element there? If there isn't, that's your problem. If there is, then look at it's Values collection and see how many of them there are.

We can't do that for you - we can't run your code under the same conditions you can!

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