索引超出了网格行命令的范围

时间:2013-04-01 12:22:09

标签: c# asp.net

我想达到gridView一个单元格的值。但它给出的错误是'索引超出范围。必须是非负数且小于集合的大小。网格行命令'

有人能帮助我吗?

 <asp:GridView ID="grdList" runat="server" AutoGenerateColumns="False"  GridLines="None"
            PageSize="5" AllowPaging="True" OnPageIndexChanging="Grd_Allergys_PageIndexChanging"
            OnRowCommand="grdList_RowCommand" OnRowDeleting="grdList_RowDeleting" OnRowEditing="grdList_RowEditing">
            <Columns>
                <asp:BoundField DataField="LangId" HeaderText="LangId" />
                <asp:BoundField DataField="LangName" HeaderText="LangName" />
                <asp:TemplateField HeaderText="Edit">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnEdit" runat="server" CommandName="Edit" CommandArgument='<%#Eval("LangId") %>'
                            ImageUrl="~/Image/edit.jpg" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnDelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("LangId")%>'
                            ImageUrl="~/Image/delete_icon.gif" OnClientClick="return confirm('Do you want to continue ?')" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <PagerSettings Mode="Numeric" />
        </asp:GridView>

 protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
 {
        DBDataContext dc = new DBDataContext();

        if (e.CommandName == "Edit")
        {                       
           int rowIndex = int.Parse(e.CommandArgument.ToString());
           string LangName = grdList.DataKeys[rowIndex]["LangName"].ToString();                              
        }                    
 }

4 个答案:

答案 0 :(得分:1)

您正在分配LangId并在命令参数中将其假设为行index。如果id大于行数,那么您应该超出范围index

更改

CommandArgument='<%#Eval("LangId")%>'

CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'

答案 1 :(得分:0)

您还没有设置DataKeys

DataKeys="LangName"添加到GridView定义中。

答案 2 :(得分:0)

commandargument = <%# Container.DisplayIndex %>

答案 3 :(得分:0)

之前我遇到过同样的问题,这是我找到的解决方案。

RowCommand 中,第一行必须是:

if (e.CommandName == "Page") return;