索引超出范围.必须为非负数 [英] Index was out of range. Must be non-negative

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

问题描述

这是我的代码;

here is my code;

protected void Del_Button_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GD1.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("Chkid");
            if (chk.Checked)
            {
             int dr = Convert.ToInt32(GD1.DataKeys[row.RowIndex].Values[0]);

            SqlParameter[] param_add_user = new SqlParameter[] 
            {
               new SqlParameter("@Sno",dr)
            };
                SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Del", null);
            }
        }
        BindData();
    }



我遇到错误...........索引超出范围.必须为非负数且小于集合的大小.



i got error...........Index was out of range. Must be non-negative and less than the size of the collection.

推荐答案

错误可能在该行中
The error could be in the line
int dr = Convert.ToInt32(GD1.DataKeys[row.RowIndex].Values[0]);


因为,如果GD1.Rows为空,则不会执行foreach 循环.如果将null作为chk返回,则将抛出Null Reference exception.这意味着执行可能会持续到上一行,并且row.RowIndex.Values[0]
中可能存在错误
在此行之后放置一个断点,当代码执行在那里停止时,检查row.RowIndex and .Values[0]
的值
我认为这可能会有所帮助.


because, the foreach loop will not execute if the GD1.Rows is empty. If null is returned as chk , then Null Reference exception would have been thrown. That means the execution may be continuing upto the above line and there may be error either in row.RowIndex or .Values[0]

Put a break point just after this line and when code execution stops there, check the value of row.RowIndex and .Values[0]

I think it may be helpful.


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

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