如何解决索引超出范围.必须是非负数并且小于集合的大小? [英] how to solve index was out of range. must be non-negative and less than the size of the collection?

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

问题描述



谁能知道这一点.

如何解决索引超出范围.必须为非负数且小于
的大小 集合吗?

代码是:

Hi,

Can anyone know this.

how to solve index was out of range. must be non-negative and less than the size of
the collection?

code is:

protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
   {
       int id = GridView1.EditIndex;
       GridViewRow rows = GridView1.Rows[e.RowIndex];
       int row = Convert.ToInt32(GridView1.DataKeys[id].Value.ToString());
       if (((TextBox)rows.FindControl("txtname") != null) && ((TextBox)rows.FindControl("txtaddress") != null))
       {
           TextBox txtname = (TextBox)rows.FindControl("txtname");
           TextBox txtaddress = (TextBox)rows.FindControl("txtaddress");
           con.Open();
           SqlCommand cmd = new SqlCommand("update employee set emp_name='" + txtname.Text + "',emp_address='" + txtaddr.Text + "' where emp_id='" + id + "", con);
           cmd.ExecuteNonQuery();
           GridView1.EditIndex = -1;
           con.Close();
           bind_grid();
       }
   }

推荐答案

没有实际可用的代码,我们无法做到那么精确.

但是错误非常清楚:您正在使用某种形式的索引(列表,数组或其他形式)的集合来使用负数或大于该集合中最后一个值的索引的索引.

例如,如果您有循环访问的列表或数组,则循环计数器必须小于项目计数:
Without the actual code to work from, we can''t be that precise.

But the error is pretty clear: You are accessing a collection of some form (list, array or other) using an index which is either negative, or larger than the index of the last value in the collection.

For example, if you have a list or an array that you are accessing in a loop, the loop counter must be less than the items count:
for (int i = 0; i < myCollection.Length; i++)
   {
   Console.WriteLine(myCollection[i]);
   }

会很好,但是

Will be fine, but

for (int i = 1; i <= myCollection.Length; i++)
   {
   Console.WriteLine(myCollection[i]);
   }

不会.


您可以检查索引是否在以下范围内:
You can check if your index is in the range :
string[] arr = new string[3];
if(index < arr.Length) // check if in range
   string s = arr[index];


GridView1.DataKeys.exists(key)
GridView1.DataKeys.exists(key)


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

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