Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

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: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). 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

like image 912
Mark Allison Avatar asked Nov 03 '10 08:11

Mark Allison


3 Answers

You need to bind your GridView every time you change page.

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.

Sorting can become quite difficult when doing this, though.

You can always use an ObjectDataSource instead of a SqlDatasource. You can then point your ObjectDataSource to look at your DB.GetTrades() function. Sorting and Paging will work automatically.

Hope that helps.

like image 182
Jamie Avatar answered Oct 08 '22 07:10

Jamie


You can create a method to for binding the grid view instead of Binding it again in 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();     }  } 
like image 34
Anil Avatar answered Oct 08 '22 08:10

Anil


I had to make my _PageIndexChanging counter to public (I'm so new at asp.net that I have no idea why it matters). 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:

<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

like image 35
brendan62269 Avatar answered Oct 08 '22 07:10

brendan62269