Asp.net GridView分页问题

Asp.net GridView分页问题,asp.net,gridview,Asp.net,Gridview,我的一个页面上有一个非常简单的GridView,在.aspx页面上有以下标记: <asp:GridView ID="gvNews" runat="server" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" DataKeyNames="NewsID,VersionStamp" OnPageIndexChanging="gvNews_PageIndexChanging"

我的一个页面上有一个非常简单的GridView,在.aspx页面上有以下标记:

<asp:GridView ID="gvNews" runat="server" AutoGenerateColumns="false" AllowPaging="true"
            AllowSorting="true" DataKeyNames="NewsID,VersionStamp" OnPageIndexChanging="gvNews_PageIndexChanging"
            OnRowCreated="gvNews_RowCreated">
            <Columns>
                <asp:BoundField HeaderText="News Title" DataField="NewsTitle"
                    SortExpression="NewsTitle" ReadOnly="true" />
                <asp:BoundField HeaderText="News Content" DataField="NewsContent"
                    SortExpression="NewsContent" ReadOnly="true" />
                <asp:BoundField HeaderText="Posted Date" DataField="InsertedDate"
                    SortExpression="InsertedDate" ReadOnly="True" />
                <asp:BoundField HeaderText="InsertedBy" DataField="InsertedBy" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lbEdit" runat="server" Text="Edit" CommandName="Select" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
在RowCreated事件中,我试图在gridview中隐藏InsertedBy列。当AllowPaging设置为flase时,此代码工作正常。但是当AllowPaging设置为true时,在RowCreated事件处理程序中会出现以下错误:

指定的参数超出了有效值的范围。 参数名称:索引


这种行为的原因可能是什么?

从您在RowCreated事件中发布的硬编码值3来看,似乎是问题所在。在页面上启用跟踪,然后查看得到的结果。顺便说一句,pager next->prev链接也会导致回发,在PageLoad中,只有当您尝试转到下一页并触发创建的行时,如果不是回发,您才加载网格。

您需要这样编写代码:

protected void gvNews_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[3].Visible = false;
    }
}

在GridView中,可能会创建不同类型的行,它们的单元格数量也不同,但RowCreated事件将针对所有行触发,因此在这种情况下,您需要将逻辑限制为仅数据行。

谢谢,这非常有效。我们还需要检查标题行,以便标题和数据行都不可见:如果e.row.RowType==DataControlRowType.DataRow | | e.row.RowType==DataControlRowType.header{e.row.Cells[3]。Visible=false;}
protected void gvNews_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[3].Visible = false;
    }
}