指数超出范围。必须是非负的[重复] [英] Index out of range.must be non-negative [duplicate]

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

问题描述

private void SaveCheckBoxState()
    {
        ArrayList employeeIDs = new ArrayList();
        int index = -1 ;

        foreach (GridViewRow row in GridView1.Rows)
        {
            **index = (int)GridView1.DataKeys[row.RowIndex].Value;**
            bool result = ((CheckBox)row.FindControl("chkcheck")).Checked;

            if (Session["Selected"] != null)
            {
                employeeIDs = (ArrayList)Session["Selected"];
            }

            if (result)
            {
                if (!employeeIDs.Contains(index))
                {
                    employeeIDs.Add(index);
                }
            }
            else
            {
                employeeIDs.Remove(index);
            }
        }
        if (employeeIDs != null && employeeIDs.Count > 0)
        {
            Session["Selected"] = employeeIDs;
        }
    }




i got this error at runtime plz try to solve this Error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index





我尝试过:



i try int index = 0;

但这也行不通



What I have tried:

i try int index=0;
but this also not work

推荐答案

这可能取决于你的数据,我们无法访问。

从使用调试器开始,并在该行上设置一个断点:

This is probably going to depend on your data, which we don't have access to.
Start start by using the debugger, and set a breakpoint on the line:
index = (int)GridView1.DataKeys[row.RowIndex].Value;

当它到达断点时,执行应该停止,让你看看在发生了什么。

在行,它是RowIndex属性,然后检查对着DataKeys集合。

猜测,它是空的,所以你得到错误。

快速查看文档 GridView.DataKeys属性(System.Web.UI.WebControls) [ ^ ]说它可能是DataKeyNames的设置属性 - 但是你需要在运行时查看数据以确切确认你拥有的数据。

When it hits the breakpoint, execution should stop, and let you look at what is going on.
At at the row, and it's RowIndex property, then check that against the DataKeys collection.
At a guess, it's empty, so you get the error.
A quick look at the documentation GridView.DataKeys Property (System.Web.UI.WebControls)[^] says it might be the setting of the DataKeyNames property - but you need to look at the data while it's running to confirm exactly what you have.


你应该学习尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

int index = -1 ;



肯定是第一个问题。

检查 GridView1 employeeIDs

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

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