指数超出范围。必须是非负数据键(Asp.Net)

时间:2012-08-24 15:53:13

标签: c# asp.net

我的代码是(Asp.Net,C#)

    int index = Convert.ToInt16(e.CommandArgument);
    string str = GridView2.DataKeys[index].Value.ToString();
    Session["studyuid2"] = str;

第二行告诉我错误索引超出范围。必须是非负数且小于集合的大小。 参数名称:index

我的gridview是

<asp:GridView ID="GridView2" runat="server" AllowPaging="True" Height="100px" 
                    RowStyle-Height="25px" HeaderStyle-Height="30px" FooterStyle-Height="30px" 
                    CellPadding=5 CellSpacing=5  
                    AutoGenerateColumns="False" 
                    DataSourceID="SqlDataSource1" EnableModelValidation="True" 
                    Width="100%" 
                    DataKeyNames="StudyUID" 
                    onrowcommand="GridView2_RowCommand" 
                    AllowSorting="True">
<RowStyle Height="25px"></RowStyle>
                    <Columns>

-------------------------------

                    </Columns>

<FooterStyle Height="30px"></FooterStyle>

<HeaderStyle Height="30px"></HeaderStyle>
                </asp:GridView>

1 个答案:

答案 0 :(得分:2)

在这种情况下,添加更多错误处理会很有帮助。遗憾的是ArgumentOutOfRangeException没有告诉你参数的值和有效范围。你可以这样做,然后它会帮你调试。

int index = Convert.ToInt16(e.CommandArgument);

try
{
    string str = GridView2.DataKeys[index].Value.ToString();
    Session["studyuid2"] = str;
}
catch (ArgumentOutOfRangeException ex) 
{
    throw new ArgumentOutOfRangeException(
        String.Format(
            "The index passed is not valid for the collection.  The index is '{0}' and must be between 0 and '{1}'.",
            index,
            GridView2.DataKeys.Count));
}

您也可以在调用DataKeys[index]之前验证索引,而不是依赖异常处理来捕获和重新抛出。

相关问题