Wednesday, July 25, 2007

How to Add Additional Element to GridView Pager without PagerTemplate

PagerTemplate allows to create any configuration of pager but it also requires custom paging to be implemented. Sometimes built-in paging completely meet all needs but a little modification is reduired, for example, ability to change page size. That can be done within RowCreated event handler.

<asp:GridView ID="GridView1" runat=server AllowPaging="True" OnRowCreated="GridView1_RowCreated" ...
Code behind:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = new DropDownList();
//adds variants of pager size
ddl.Items.Add("5");
ddl.Items.Add("10");
ddl.AutoPostBack = true;
//selects item due to the GridView current page size
ListItem li = ddl.Items.FindByText(GridView1.PageSize.ToString());
if (li != null)
ddl.SelectedIndex = ddl.Items.IndexOf(li);
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
//adds dropdownlist in the additional cell to the pager table
Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
TableCell cell = new TableCell();
cell.Style["padding-left"] = "15px";
cell.Controls.Add(new LiteralControl("Page Size:"));
cell.Controls.Add(ddl);
pagerTable.Rows[0].Cells.Add(cell);
}
}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
//changes page size
GridView1.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
//binds data source
GridView1.DataSource = ...;
GridView1.DataBind();
}
Source code - 1.9 kB

No comments:

Post a Comment