GridView 不显示 GridView_PageIndexChanging

GridView don't Show on GridView_PageIndexChanging

我有一个 ViewStock 面板,我在其中查看来自数据库的 gridview 中的股票,并通过代码对其进行 DataBind()。允许在 html 中的 gridview 标记中分页和创建事件 "OnPageIndexChanging",实现上面定义的代码并在事件中分页如下:

HTML:

<asp:Panel ID="Panel_StockView" runat="server">

    <asp:GridView ID="GridView_Stock" AllowPaging="true" OnPageIndexChanging="GridView_PageIndexChanging" runat="server"></asp:GridView>

</asp:Panel>

C# 代码:

protected void LinkButton_Panel_ViewStock_Click(object sender, EventArgs e)
{
    using(SqlConnection con = new SqlConnection(cs))
    {
        //Sql command here
        /sql adapter and filled datatable
        sdaStockView.Fill(dtStockView);
        GridView_Stock.DataSource = dtStockView;
        GridView_Stock.DataBind();
    }
}

现在实现分页

protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView_Stock.DataBind();
    GridView_Stock.PageIndex = e.NewPageIndex;
}

它确实有效,但部分有效。它进行分页并正确处理数据。但是,问题是当我单击页面“2”时,面板会像我上传的图片一样空白 See this Image,然后我单击 link 按钮再次将我重定向到面板并打开包含有效数据的 gridview 页面“2”。

如何解决这个问题?

像这样填写 DataSet 后,将 DataSet 保存在 LinkButton_Panel_ViewStock_Click 上的 ViewState 某处

ViewState["ds"] = dtStockView

PageIndexChanging这样写

protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    panel_ViewStock.visible = true;
    GridView_Stock.PageIndex = e.NewPageIndex;
    GridView_Stock.DataSource = ViewState["ds"] as DataSet
    GridView_Stock.DataBind();
}

希望对您有所帮助

  1. 将 GridView 绑定到数据的逻辑提取到一个新的 method.You 中,可以调用它 BindData() 例如:

    private void BindData()
    {
        using (SqlConnection con = new SqlConnection(cs))
        {
            sdastockview.fill(dtstockview);
            gridview_stock.datasource = dtstockview;
            gridview_stock.databind();
        }
    }
    
  2. LinkButton_Panel_ViewStock_Click 中调用此方法来填充 GridView:

    protected void LinkButton_Panel_ViewStock_Click(object sender, EventArgs e)
    {
        this.BindData();
    }
    
  3. 最后,在分页时再次调用它重新填充GridView

    protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView_Stock.PageIndex = e.NewPageIndex;
        this.BindData();
    }
    

只需进行这三个小改动,它就会起作用。我已经在我这边试过了,它工作得很好。

您可以尝试使用:

protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)