指数超出范围。必须是非负数且小于集合的大小。 [英] Index was out of range. Must be non-negative and less than the size of the collection.

查看:72
本文介绍了指数超出范围。必须是非负数且小于集合的大小。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我更新gridview中的行时,此错误即将到来

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.





我尝试过: < br $>




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();
          }

推荐答案

从调试器开始,查看索引 - 很可能是 e.RowIndex 为-1,因为没有选择任何内容。如果是这种情况,您需要添加代码以专门检查负值,因为在启动时通常会为某些事件获得至少一个负值。
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.


这篇关于指数超出范围。必须是非负数且小于集合的大小。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆