Tuesday, November 22, 2011

Custom pager inside the gridview pager template using c#

In previous articles how to sort and paging in gridview in asp.net,The pager template in gridview is a certain layout. it would be to show the current page and number of pages[index].For this I have used a HTML table to create a custom page in side the grid view Pager template.We have two more function in this code which are create page numbers in grid view pager template
Aspx page:


<asp:gridview allowpaging="True" autogeneratecolumns="False" autogenerateselectbutton="True" cellpadding="4" font-names="Verdana" gridlines="None" id="GdvMainmasters" ondatabound="GdvMainmasters_DataBound" onpageindexchanging="GdvMainmasters_PageIndexChanging" onrowcommand="GdvMainmasters_RowCommand" runat="server">

<columns>



<asp:templatefield headertext="CODE">
<itemtemplate>
<asp:label id="lblmaincode" runat="server" text="<%# Bind("MAINCODE") %>"></asp:label>
</itemtemplate>
</asp:templatefield>

<asp:templatefield headertext="NAME">
<itemtemplate>
<asp:label id="lblmainnanme" runat="server" text="<%#  Bind("MAINNAME")%>"></asp:label>
</itemtemplate>
<itemstyle width="300px">
</itemstyle></asp:templatefield>


<asp:templatefield headertext="STATUS">
<itemtemplate>
<asp:label id="lblstatus" runat="server" text="<%# Bind("STATUS")%>"></asp:label>
</itemtemplate>
<itemstyle width="300px">
</itemstyle></asp:templatefield>

</columns>

<pagerstyle backcolor="White" borderstyle="Double" forecolor="Black" horizontalalign="Center">
<pagertemplate>
</pagertemplate>
</pagerstyle>

</asp:gridview>


<table class="pagerOuterTable" id="pagerOuterTable" runat="server"><tbody>
<tr><td><br />
<br />
<table cellpadding="2" cellspacing="1" id="pagerInnerTable" runat="server"><tbody>
<tr>
<td class="pageCounter">
<br />
<asp:label id="lblPageCounter" runat="server" text=""></asp:label></td> <td class="pageFirst"><br />
<br />

<img align="middle" alt="" src="Images/firstpage.gif" /><br />

<asp:linkbutton commandargument="First" commandname="Page" cssclass="pagerLink" id="lnkFirstPage" runat="server">First</asp:linkbutton></td>   <td class="pagePrevtNumber"><br />

<asp:linkbutton commandargument="Prev" commandname="Page" cssclass="pagerLink" id="linkprevpage" onclick="linkprevpage_Click" runat="server">Prev</asp:linkbutton></td>   <td class="pageNextNumber"><br />

<asp:linkbutton commandargument="next" commandname="Page" cssclass="pagerLink" id="linknextpage" onclick="linknextpage_Click" runat="server">Next</asp:linkbutton></td>   <td class="pageLast"><br />

<asp:linkbutton commandargument="Last" commandname="Page" cssclass="pagerLink" id="lnkLastPage" runat="server">Last</asp:linkbutton>&nbsp;<img align="middle" alt="" src="Images/lastpage.gif" /></td>     </tr>

</tbody>
</table>
</td>
<td class="pageGroups" visible="false">
<br />
Pages:<asp:dropdownlist autopostback="true" id="ddlPageGroups" onselectedindexchanged="ddlPageGroups_SelectedIndexChanged" runat="server"></asp:dropdownlist>
</td>
</tr>
</tbody>
</table>

Code Behind:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
using dpant;
using System.Drawing;
using System.Threading;

public partial class _Default : System.Web.UI.Page
{

 public static string connection = ConfigurationManager.ConnectionStrings  ["Con"].ToString();
 public static SqlConnection con = new SqlConnection(connection);
 public static SqlCommand cmd = null;
 protected FullGridPager fullGridPager;
 protected int MaxVisible = 10;
   
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
fullGridPager = new FullGridPager(GdvMainmasters,MaxVisible, "Page", "of");
fullGridPager.CreateCustomPager(GdvMainmasters.BottomPagerRow);
}
}
protected void GdvMainmasters_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
GdvMainmasters.PageIndex = e.NewPageIndex;
GdvMainmasters.DataBind();        
}

protected void GdvMainmasters_DataBound(object sender, EventArgs e)
{
if (Excelbtn != "ABC" )
{
if (fullGridPager == null)
{
fullGridPager = new FullGridPager(GdvMainmasters, MaxVisible, "Page", "of");
}
fullGridPager.CreateCustomPager(GdvMainmasters.BottomPagerRow);
fullGridPager.PageGroups(GdvMainmasters.BottomPagerRow);
}
}

protected void ddlPageGroups_SelectedIndexChanged(object sender,EventArgs e)
{
if (fullGridPager == null)
{
fullGridPager = new FullGridPager(GdvMainmasters, MaxVisible, "Page", "of");
}
fullGridPager.PageGroupChanged(GdvMainmasters.BottomPagerRow);
}

protected void linknextpage_Click(object sender, EventArgs e)
{
GdvMainmasters.PageIndex = GdvMainmasters.PageIndex + 10;
GdvMainmasters.DataBind();
}

protected void linkprevpage_Click(object sender, EventArgs e)
{
if (GdvMainmasters.PageIndex > 10)
{
GdvMainmasters.PageIndex = GdvMainmasters.PageIndex - 10;
GdvMainmasters.DataBind();
}
else
GdvMainmasters.PageIndex = 0;
GdvMainmasters.DataBind();
}
}

Here i have created a class protected FullGridPager fullGridPager;
to develop the custom paging,and number for grid view.Because i have multiple pages with same grid view pager.
protected FullGridPager fullGridPager class;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace dpant
{


public class FullGridPager
{
    private const int DEFAULT_MAX_VISIBLE = 0;
    private const string DEFAULT_COUNTER_TEXT = "";
    private const string DEFAULT_TOTAL_TEXT = "";
                
    protected int maxVisiblePageNumbers;
    protected int firstPageNumber;
    protected int lastPageNumber;
    protected string pageCounterText;
    protected string pageCounterTotalText;
    protected GridView theGrid;
    protected GridViewRow theGridViewRow;
    

public FullGridPager(GridView TheGrid)
{
// Default Constructor  
maxVisiblePageNumbers = DEFAULT_MAX_VISIBLE;
pageCounterText = DEFAULT_COUNTER_TEXT;
pageCounterTotalText = DEFAULT_TOTAL_TEXT;
theGrid = TheGrid;
}

public FullGridPager(GridView TheGrid, int MaxVisible, string CounterText, string TotalText)
{
// Parameterized constructor
maxVisiblePageNumbers = MaxVisible;
pageCounterText = CounterText;
pageCounterTotalText = TotalText;
theGrid = TheGrid;
}
    
public int MaxVisiblePageNumbers
{
get { return maxVisiblePageNumbers; }
set { maxVisiblePageNumbers = value; }
}

public string PageCounterText
{
get { return pageCounterText; }
set { pageCounterText = value; }
}
  
public string PageCounterTotalText
{
get { return pageCounterTotalText; }
set { pageCounterTotalText = value; }
}
       
public GridView TheGrid
{
get { return theGrid; }
}
   
public void CreateCustomPager(GridViewRow PagerRow)
{
// Create custom pager inside the Grid's pagerTemplate.
// An html table is used to format the custom pager.
// No data to display.
if (PagerRow == null) return;
theGridViewRow = PagerRow;
HtmlTable pagerInnerTable = (HtmlTable)PagerRow.Cells[0].FindControl("pagerInnerTable");
if (pagerInnerTable != null)
{
// default dynamic cell position. 
// (after the pageCount, the "First" and the "Previous" cells).            
int insertCellPosition = 2;
if (theGrid.PageIndex == 0)
{
// The first page is currently displayed.
// Hide First and Previous page navigation.
pagerInnerTable.Rows[0].Cells[1].Visible = false;
pagerInnerTable.Rows[0].Cells[2].Visible = false;
// Change the default dynamic cell to 1.
insertCellPosition = 0;
}

CalcFirstPageNumber();
CalcLastPageNumber();
CreatePageNumbers(pagerInnerTable, insertCellPosition);
int lastCellPosition = pagerInnerTable.Rows[0].Cells.Count - 1;
if (theGrid.PageIndex == theGrid.PageCount - 1)
{
// The last page is currently displayed.
// Hide Next and Last page navigation.                
pagerInnerTable.Rows[0].Cells[lastCellPosition - 1].Visible = false;
pagerInnerTable.Rows[0].Cells[lastCellPosition].Visible = false;
}
UpdatePageCounter(pagerInnerTable);
}
}

private void CreatePageNumbers(HtmlTable pagerInnerTable, int insertCellPosition)
{
for (int i = firstPageNumber, pos = 1; i <= lastPageNumber; i++, pos++)
{
// Create a new table cell for every data page number.
HtmlTableCell tableCell = new HtmlTableCell();
if (theGrid.PageIndex == i - 1)
tableCell.Attributes.Add("class", "pageCurrentNumber");
else
tableCell.Attributes.Add("class", "pagePrevNextNumber");
// Create a new LinkButton for every data page number.
LinkButton lnkPage = new LinkButton();
lnkPage.ID = "Page" + i.ToString();
lnkPage.Text = i.ToString();
lnkPage.CommandName = "Page";
lnkPage.CommandArgument = i.ToString();
lnkPage.CssClass = "pagerLink";
// Place link inside the table cell; Add the cell to the table row.                
tableCell.Controls.Add(lnkPage);
pagerInnerTable.Rows[0].Cells.Insert(insertCellPosition + pos, tableCell);
}
}

private void CalcFirstPageNumber()
{
// Calculate the first, visible page number of the pager.             
firstPageNumber = 1;
if (MaxVisiblePageNumbers == DEFAULT_MAX_VISIBLE)
MaxVisiblePageNumbers = theGridPageCount;
if (theGrid.PageCount > MaxVisiblePageNumbers)
{
// Seperate page numbers in groups if necessary.
if ((theGrid.PageIndex + 1) > maxVisiblePageNumbers)
{
// Calculate the group to display.
// Example: 
//      GridView1.PageCount = 12
//      maxVisiblePageNumbers = 4
//      GridView1.PageIndex+1 = 7
//      --> pageGroup = 2       (Page numbers: 5, 6, 7, 8)
decimal pageGroup = Math.Ceiling((decimal)(theGrid.PageIndex + 1) / MaxVisiblePageNumbers);
// Calculate the first page number for the group to display.
// Example :
//      if pageGroup = 1 (Page numbers: 1,2,3,4) --> firstPageNumber = 1
//      if pageGroup = 2 (Page numbers: 5,6,7,8) --> firstPageNumber = 5
//      if pageGroup = 3 (Page numbers: 9,10,11,12) --> firstPageNumber = 9               firstPageNumber = (int)(1 + (MaxVisiblePageNumbers * (pageGroup - 1)));
}
}
}

private void CalcLastPageNumber()
{
// Calculate the last, visible page number of the pager.
lastPageNumber = theGrid.PageCount;
if (MaxVisiblePageNumbers == DEFAULT_MAX_VISIBLE)
MaxVisiblePageNumbers = theGrid.PageCount;
if (theGrid.PageCount > MaxVisiblePageNumbers)
{
lastPageNumber = firstPageNumber + (MaxVisiblePageNumbers - 1);
if (theGrid.PageCount < lastPageNumber)
lastPageNumber = theGrid.PageCount;
}
}

private void UpdatePageCounter(HtmlTable pagerInnerTable)
{
// Display current page number and total number of pages.        
Label pageCounter = (Label)pagerInnerTable.Rows[0].Cells[0].FindControl("lblPageCounter");
pageCounter.Text = " " + PageCounterText + " " + (theGrid.PageIndex + 1).ToString() + " " + PageCounterTotalText + " " + theGrid.PageCount.ToString() + " ";
}

public void PageGroups(GridViewRow PagerRow)
{
// Display page groups in pager if GridView.PageCount is greater than the maxVisiblePageNumbers.
        
// No data to display.
if (PagerRow == null) return;
theGridViewRow = PagerRow;
HtmlTable pagerOuterTable = (HtmlTable)PagerRow.Cells[0].FindControl("pagerOuterTable");I
If (MaxVisiblePageNumbers == DEFAULT_MAX_VISIBLE)
MaxVisiblePageNumbers = theGrid.PageCount;
int maxPageGroups = (int)Math.Ceiling((decimal)theGrid.PageCount / MaxVisiblePageNumbers);
if (theGrid.PageCount > MaxVisiblePageNumbers)
{
int lastCellPosition = pagerOuterTable.Rows[0].Cells.Count - 1;
decimal pageGroup = Math.Ceiling((decimal)(theGrid.PageIndex + 1) / MaxVisiblePageNumbers);

DropDownList ddlPageGroups = (DropDownList)pagerOuterTable.Rows[0].Cells[lastCellPosition].FindControl("ddlPageGroups");
 for (int pg = 1; pg <= maxPageGroups; pg++)
{
int groupFirstPageNumber = (int)(1 + (maxVisiblePageNumbers * (pg - 1)));
int groupLastPageNumber = groupFirstPageNumber + (maxVisiblePageNumbers - 1);
if (theGrid.PageCount < groupLastPageNumber)
groupLastPageNumber = theGrid.PageCount;
string group = String.Format("{0} ... {1}", groupFirstPageNumber.ToString(), groupLastPageNumber.ToString());
ListItem groupItem = new ListItem(group, groupFirstPageNumber.ToString());
if (pageGroup == pg)
groupItem.Selected = true;
ddlPageGroups.Items.Add(groupItem);
}
 //Make the dropdownlist visible;
pagerOuterTable.Rows[0].Cells[lastCellPosition].Visible = false;
}
}
public void PageGroupChanged(GridViewRow PagerRow)
{
 // Change the page group.        
if (PagerRow != null)
{
 HtmlTable pagerOuterTable = (HtmlTable)PagerRow.Cells[0].FindControl("pagerOuterTable");
 int lastCellPosition = pagerOuterTable.Rows[0].Cells.Count - 1;
  DropDownList ddlPageGroups = (DropDownList)pagerOuterTable.Rows[0].Cells[lastCellPosition].FindControl("ddlPageGroups");
  this.theGrid.PageIndex = Int32.Parse(ddlPageGroups.SelectedValue) - 1;
}
}
}
}
Post a Comment

Bel