简体   繁体   English

如何以编程方式在ASP.NET 4.0 GridView上启用分页和排序?

[英]How to enable Paging and Sorting on ASP.NET 4.0 GridView programmatically?

I am using ASP.NET 4.0 with C# (Visual Web Developer 2010 Express). 我使用ASP.NET 4.0与C#(Visual Web Developer 2010 Express)。

I have successfully managed to implement a simple GridView bound to a stored procedure data source using declarative ASP.NET code as shown here: 我已成功设法使用声明性ASP.NET代码实现绑定到存储过程数据源的简单GridView,如下所示:

<asp:GridView 
    ID="grdTrades" 
    runat="server" 
    DataKeyNames="tradeId" 
    EnablePersistedSelection="true"
    SelectedRowStyle-BackColor="Yellow" 
    AllowPaging="true" 
    AllowSorting="true"
    PageSize = "20" 
    AutoGenerateColumns="false" 
    DataSourceID="sdsTrades" 
    >
    <Columns>
        <asp:CommandField ShowSelectButton="true" ButtonType="Link" SelectText="Select" />
        <asp:BoundField DataField="tradeId" HeaderText="TradeId"  ReadOnly="True" SortExpression="tradeId" />
        < ... more columns ... >
    </Columns>
</asp:GridView>

<asp:SqlDataSource ID="sdsTrades" runat="server" 
    ConnectionString="<%$ ConnectionStrings:TradesDB %>" 
    ProviderName="<%$ ConnectionStrings:Trades.ProviderName %>"  
    SelectCommand="usp_GetTrades" SelectCommandType="StoredProcedure">      
</asp:SqlDataSource>

It works great including paging and sorting. 它工作得很好,包括分页和排序。 I want to remove the SqlDataSource and use code-behind (I'm trying to put database access code in one place). 我想删除SqlDataSource并使用代码隐藏(我试图将数据库访问代码放在一个地方)。 So far I have this in my code-behind: 到目前为止,我在我的代码隐藏中有这个:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        grdTrades.SelectedIndex = 0;
        DBUtil DB = new DBUtil();
        grdTrades.DataSource = DB.GetTrades();
        grdTrades.DataKeyNames = new string[] { "tradeId" };
        grdTrades.DataBind();            
    }
}

// this is needed otherwise I get "The GridView 'grdTrades' fired event PageIndexChanging which wasn't handled."
void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
    grdTrades.PageIndex = e.NewPageIndex;
    grdTrades.DataBind();
}    

My declarative code now looks like: 我的声明代码现在看起来像:

<asp:GridView 
    ID="grdTrades" 
    runat="server" 
    EnablePersistedSelection="true"            
    SelectedRowStyle-BackColor="Yellow" 
    AllowPaging="true" 
    AllowSorting="true"
    PageSize = "20" 
    AutoGenerateColumns="false" 

    OnPageIndexChanging="grdTrades_PageIndexChanging"
    >
    <Columns>
        <asp:CommandField ShowSelectButton="true" ButtonType="Link" SelectText="Select" />
        <asp:BoundField DataField="tradeId" HeaderText="TradeId"  ReadOnly="True" SortExpression="tradeId" />
        < ... more columns ... >           
    </Columns>
</asp:GridView>

The problem is when I click on a page number the page becomes blank. 问题是,当我点击页码时,页面变为空白。 I would also like to implement sorting but would like to get the paging working first. 我还想实现排序,但希望首先使分页工作。 Please help. 请帮忙。

Thanks 谢谢

You need to bind your GridView every time you change page. 每次更改页面时都需要绑定GridView。

For example: 例如:

void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e) 
{
    grdTrades.DataSource = DB.GetTrades();  
    grdTrades.PageIndex = e.NewPageIndex; 
    grdTrades.DataBind(); 
} 

My advice would be to store your results from DB.GetTrades() in the ViewState (or Cache) so you don't need to go to the database everytime you change page. 我的建议是将结果存储在ViewState(或Cache DB.GetTrades()中的DB.GetTrades()中,这样每次更改页面时都不需要转到数据库。

Sorting can become quite difficult when doing this, though. 但是,在执行此操作时,排序会变得非常困难。

You can always use an ObjectDataSource instead of a SqlDatasource. 您始终可以使用ObjectDataSource而不是SqlDatasource。 You can then point your ObjectDataSource to look at your DB.GetTrades() function. 然后,您可以指向ObjectDataSource以查看DB.GetTrades()函数。 Sorting and Paging will work automatically. 排序和分页将自动运行。

Hope that helps. 希望有所帮助。

You can create a method to for binding the grid view instead of Binding it again in Paging. 您可以创建一种方法来绑定网格视图,而不是在Paging中再次绑定它。 By creating a method that binds the Grid View you can always call the method to Bind the grid view whenever you want. 通过创建绑定网格视图的方法,您始终可以调用方法以随时绑定网格视图。

protected void Page_Load(object sender, EventArgs e)
{
   if (!this.IsPostBack)
   {
       BindgrdTrades();            
   }
private void BindgrdTrades()
   {
      DBUtil DB = new DBUtil();
       grdTrades.DataSource = DB.GetTrades();
       grdTrades.DataKeyNames = new string[] { "tradeId" };
       grdTrades.DataBind(); 
   }
}

void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e) 
   {

       grdTrades.PageIndex = e.NewPageIndex; 
       BindgrdTrades(); 
   } 
}

I had to make my _PageIndexChanging counter to public (I'm so new at asp.net that I have no idea why it matters). 我不得不将我的_PageIndexChanging计数器公开(我在asp.net上这么新,我不知道为什么这很重要)。 The page would through an error saying it couldn't find the class. 该页面将通过一个错误说它无法找到该类。 These posts were a great help to get paging working with otherwise near verbatim logic. 这些帖子对于使用其他接近逐字逻辑的分页工作有很大帮助。 Thanks to all the posters for taking the time to lay it out so clearly. 感谢所有海报花时间如此清晰地展示出来。 Here's the code I ended up with: 这是我最终得到的代码:

public partial class Requests : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!this.IsPostBack)
        {
            BindgrdBuilds();

        }
    }

    private void BindgrdBuilds()
    {
        // Link GridView to datasource
        GridView1.DataSource = BuildData.getBuilddata();

        // Bind SQLDataSource to GridView after retrieving the records.
        GridView1.DataBind();

    }

    public void GridView1_PageIndexChanging(Object sender, GridViewPageEventArgs e)
    {
        // increment PageIndex
        GridView1.PageIndex = e.NewPageIndex;

        // bind table again
        BindgrdBuilds();

    } 
}

I stuck with AutoGenerated columns, and I'm doing some row binding to my data on the cs page that I didn't include above, but here's my asp code for the GridView: 我坚持使用AutoGenerated列,并且我正在对我在上面没有包含的cs页面上的数据进行一些行绑定,但这里是我的GridView的asp代码:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1" 
    OnRowDataBound="GridView1_RowDataBound" 
    OnPageIndexChanging="GridView1_PageIndexChanging"
    runat="server" 
    SelectedRowStyle-BackColor="Yellow" 
    AllowPaging="true" 
    AllowSorting="true"
    PageSize = "20" 
    AutoGenerateColumns="true" 
    <-- table formatting code trimmed -->
</asp:GridView>

I hope someone else can make use of this info, this thread was a great, simple example to follow. 我希望其他人可以利用这些信息,这个帖子是一个很好的,简单的例子。 Now that paging works it's time to get real fancy and come up with a new name for GridView1 :D 现在,分页工作正是时候才能获得真正的想象力,并为GridView1:D找到一个新名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM