0

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

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

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

我的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>
4

1 回答 1

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],而不是依靠异常处理来捕获和重新抛出。

于 2012-08-24T16:02:13.657 回答