Adding Controls To ASP.NET GridView Pager Row

September 14th, 2006

ASP.NET 2.0 GridView control contains the AllowPaging property. Setting this property to a value of true enables the paging feature of the GridView and displays data split across multiple pages if the number of rows in the underlying data source is greater than the PageSize property. By default ASP.NET automatically displays numeric paging controls at the bottom of the GridView.

While automatic paging is a very handy feature of GridView, if you want to display any additional paging controls than those inherently supported by automatic paging, you must resort to specifying your own PagerTemplate and write some additional code to preform the same functionality that GridView would otherwise handle for you.

In certain situations, a better option, however, is to simply inject your custom control(s) into the pager generated by the GridView. The following example shows how we can inject a “View All” LinkButton into GridView’s pager row that allows users to view all rows in the underlying data source at the same time:

protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Pager)
    {
        LiteralControl space = new LiteralControl(" ");

        LinkButton lb = new LinkButton();
        lb.ID = "ViewAllLinkButton";
        lb.Text = "View All";
        lb.SkinID = "ProfessionalGridViewPagerViewAll";
        lb.Click += new EventHandler(ViewAllLinkButton_Click);

        // Pager is rendered in a single cell as a table;
        // each page # is in a cell by it's own
        Table table = e.Row.Cells[0].Controls[0] as Table;

        // Add ViewAll linkbutton to the last cell
        TableCell parentCell = table.Rows[0].Cells[table.Rows[0].Cells.Count - 1];
        parentCell.Controls.Add(space);
        parentCell.Controls.Add(lb);
    }
}


protected void ViewAllLinkButton_Click(object sender, EventArgs e)
{
    MyGridView.AllowPaging = false;
}
Comments are closed.