Wednesday, November 10, 2010

custom pagination in gridview

If you want to implement custom pagination having "Next" and "Prev" button in gridview then you have following options:-

http://www.codeproject.com/KB/aspnet/CustomPagingForGridview.aspx
http://msdn.microsoft.com/en-us/library/aa479347.aspx
http://dotnetslackers.com/articles/ajax/ASPNETAjaxGridAndPager.aspx

But i have got one more good solution which works well for me. See below:-

GridView1.PagerSettings.Mode = PagerButtons.NumericFirstLast;
GridView1.PagerSettings.NextPageText = ">";
GridView1.PagerSettings.PreviousPageText = "<"; GridView1.PagerSettings.LastPageText = ">>";
GridView1.PagerSettings.FirstPageText = "<<";

GridView1.RowDataBound+=new GridViewRowEventHandler(GridView1_RowDataBound); 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{
 if (e.Row.RowType == DataControlRowType.Pager) 
{ Table pagerTable = (Table)e.Row.Cells[0].Controls[0]; 
TableRow pagerRow = pagerTable.Rows[0]; 
PagerSettings pagerSettings = ((GridView)sender).PagerSettings; 
int cellsCount = pagerRow.Cells.Count; 
if (pagerSettings.Mode == PagerButtons.Numeric || pagerSettings.Mode == PagerButtons.NumericFirstLast) {
 int prevButtonIndex = pagerSettings.Mode==PagerButtons.Numeric ? 0 : 1; 
int nextButtonIndex = pagerSettings.Mode==PagerButtons.Numeric ? cellsCount-1 : cellsCount-2; 
if (prevButtonIndex < cellsCount) 
{ //check whether previous button exists LinkButton btnPrev = pagerRow.Cells[prevButtonIndex].Controls[0] as LinkButton; if (btnPrev != null && btnPrev.Text.IndexOf("...") != -1) btnPrev.Text = pagerSettings.PreviousPageText; 

if (nextButtonIndex > 0 && nextButtonIndex < cellsCount)
{
//check whether next button exists
LinkButton btnNext = pagerRow.Cells[nextButtonIndex].Controls[0] as LinkButton;
if (btnNext != null && btnNext.Text.IndexOf("...") != -1)
btnNext.Text = pagerSettings.NextPageText;
}
}
}
}

Thanks!
Avinash

No comments: