Gridview:索引超出了范围

本文关键字:范围 索引 Gridview | 更新日期: 2023-09-27 18:03:13

我有3个GridView控件在3个不同的页面。他们以前工作得很好。突然,我得到了这个错误信息:

无效的回发或回调参数。使用<pages enableeventvalidation="true" />

启用事件验证

所以我试着把<@pages enableeventvalidation="false" />放在页面上。它仍然不起作用。我把这条命令从页面上删除了。然后另一个消息显示"索引超出范围",当单击gridview中所有gridview控件的按钮时。

int id = Convert.ToInt32(myGridView.DataKeys[e.RowIndex].Value)

看起来gridview找不到数据键(e.rowIndex的值是OK), Datakeynames已经设置。

protected void gvItemCategory_RowDeleting(object sender, GridViewDeleteEventArgs e) {
    int categoryId = Convert.ToInt32(gvItemCategory.DataKeys[e.RowIndex].Value);
    CollectionCategory category = new CollectionCategory();
    category.CategoryId = categoryId; 
    category.Delete();
    ItemCateogryShowData();
}
HTML:

<asp:GridView ID="gvItemCategory" runat="server" AutoGenerateColumns="False"
OnRowCancelingEdit="gvItemCategory_RowCancelingEdit"
    OnRowDeleting="gvItemCategory_RowDeleting" OnRowEditing="gvItemCategory_RowEditing"
    DataKeyNames="CategoryId" OnRowUpdating="gvItemCategory_RowUpdating">
    <Columns>
        <asp:TemplateField HeaderText="CateogoryName">
            <ItemTemplate>
                <asp:Label ID="lblItemCategoryName" runat="server"    Text='<%#Eval("CategoryName") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbItemCateogryName" runat="server" Text='<%#Eval("CategoryName") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowEditButton="True" ButtonType="Button" />
        <asp:CommandField ShowDeleteButton="True" />
    </Columns>
    </asp:GridView>

Gridview:索引超出了范围

尝试将Gridview绑定到pageload !ispostback方法..

If(!isPostback)
{
 //your code here
}

Try this

int categoryId = Convert.ToInt32(gvItemCategory.DataKeys[e.RowIndex].Value.Tostring());

注意:也使用EnableeventValidation="false"