Customers requested the possibility to toggle the display of data in a GridView between paged view and complete view. I sketch a method to add a LinkButton in the Pager rows that performs this toggle.![]()
A GridView’s pager row is rendered in HTML as
<tr>
<td colspan="7"> <-- the number of columns in the grid
<table border="0">
<tbody><tr>
<td><span>1</span></td>
<td><a href="javascript:__doPostBack('GridView1','Page$2')">2</a></td>
... etc for each page ...
</tr></tbody>
</table>
</td>
</tr>
My approach is to insert the LinkButton right to the table containing the page selectors, by injecting a right-floating span before the page selector table in GridView_RowCreated:
protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
{
var gv = sender as GridView;
switch (e.Row.RowType)
{
case DataControlRowType.Pager:
TableCell cell = e.Row.Cells[0];
Table tbl = (Table)cell.Controls[0];
cell = tbl.Rows[0].Cells[0];
var span = new HtmlGenericControl("span");
span.Attributes["style"] = "position:relative; float:right";
span.Attributes["align"] = "right";
span.Controls.Add(new Literal
{ Text = "<table border=\"0\"><tbody><tr><td>" });
LinkButton btnPaging = new LinkButton
{ Text = IsPaging(gv) ? "All Records" : "Paged View" };
btnPaging.Click += new EventHandler(btnPaging_Click);
span.Controls.Add(btnPaging);
span.Controls.Add(new Literal
{ Text = "</td></tr></tbody></table>" });
cell.Parent.Parent.Parent.Controls.AddAt(0, span);
break;
To find out which mode a GridView is rendering, we need a little helper function
bool IsPaging(GridView gv)
{
return gv.PageSize <= 100;
}
Clicking the LinkButton will now toggle the paging mode, and we also save the PageSize to restore the previous value when clicking again:
void btnPaging_Click(object sender, EventArgs e)
{
var gv = ((LinkButton)sender).Parent.Parent
.Parent.Parent.Parent as GridView;
if (IsPaging(gv))
{
gv.Attributes["pagesize"] = gv.PageSize.ToString();
gv.PageSize = 100000;
gv.PageIndex = 0;
}
else
{
gv.PageSize = deviolib.Convert.ToIntDef(gv.Attributes["pagesize"], 20);
}
}
When I worked out this solution, I found that if the result displays in a single page, the pager is not displayed anymore. This answer on SO showed how to make it visible again: In the GridView_PreRender event, set both PagerRows’ Visible value.
void GridView_PreRender(object sender, EventArgs e)
{
var gv = ((GridView)sender);
GridViewRow pagerRow = gv.TopPagerRow;
if (pagerRow != null && pagerRow.Visible == false)
pagerRow.Visible = true;
pagerRow = gv.BottomPagerRow;
if (pagerRow != null && pagerRow.Visible == false)
pagerRow.Visible = true;
}
Posted by devio 





