【问题标题】:Error "Index was out of range" in ASP.Net applicationASP.Net 应用程序中的错误“索引超出范围”
【发布时间】:2011-08-15 12:33:26
【问题描述】:

我正在制作一个应用程序 ASP.Net / C#,其中我有一个 Gridview,每行都有一个复选框。

问题是其中一些通过选择并点击“保存”出现以下错误:

索引超出范围。必须是非负数且小于集合的大小。 \r\n参数名:索引。

而且这个错误似乎只发生在 Gridview 的最后一行。以下是代码和属性窗口Gridview的sn-p:

C#

protected void btnOKVulsProj_Click(object sender, EventArgs e)
    {

            //Variables

        for (int cont = 0; cont < grdListaVulsProj.Rows.Count; cont++)
        {
            idVul = Convert.ToInt32((grdListaVulsProj.Rows[cont].Cells[0]).Text);

            string strQueryInsert = ("INSERT TO DATABASE");

            if (((CheckBox)grdListaVulsProj.Rows[idVul].FindControl("chkSelecionaItem")).Checked)  <<< WHERE THE ERROR OCCURS

            {
                Conexao.Inserir(strQueryInsert); //Method that performs the insertion
            }
        };

            //Other instructions

    }



Gridview 属性的

http://i56.tinypic.com/33f3hqf.jpg

注意:Gridview 旨在在数据库中注册所有被选中的行。

注意 2:我广泛搜索了 Web 解决方案,但都提出了,但都没有解决我的问题。

谢谢!

[]的

【问题讨论】:

    标签: c# asp.net gridview indexing range


    【解决方案1】:

    我猜你的问题在这里:

    if (((CheckBox)grdListaVulsProj.Rows[idVul]...
    

    idVul 真的是 rows 集合的索引,还是您的意思是在那里使用 cont

    【讨论】:

    • 我认为这是正确的方法,但上面的方法更有意义。 (y)
    【解决方案2】:

    你的行应该是:

    if (((CheckBox)grdListaVulsProj.Rows[cont].FindControl("chkSelecionaItem")).Checked)  <<< WHERE THE ERROR OCCURS  
    

    【讨论】:

    • 这真的更有意义
    • 非常感谢您的精彩修复。这解决了我的问题。一个简单的逻辑错误,可能是因为我是初学者:P
    【解决方案3】:

    我经常遇到的问题是第 0 行实际上是页眉,最后一行是页脚。

    尝试这样的比较:

    if (grdListaVulsProj.Rows[cont].RowType == DataControlRowType.DataRow)
    {
    // your code here
    }
    

    【讨论】:

    • 不知道这个表格,那我也测试一下。谢谢回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多