Paging isn't always the easiest thing to figure out - and sometimes not the most performant thing you can do to a we site. Here's a webcast to show you how to set it up both ways: the ASP way, and the SubSonic way.
The code for this web cast is down below...
The HTML:
<table> <tr> <td> <asp:GridView ID="GridView1" runat="server" /> </td> </tr> <tr> <td> <asp:Button ID="btnFirst" runat="server" Text="<< First" CommandArgument="First" OnClick="pager_Click"/> <asp:Button ID="btnPrev" runat="server" Text="< Previous" CommandArgument="Prev" OnClick="pager_Click"/> Page <asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPages_SelectedIndexChanged"> </asp:DropDownList> of <asp:Label ID="lblPageCount" runat="server"></asp:Label> <asp:Button ID="btnNext" runat="server" Text="Next >" CommandArgument="Next" OnClick="pager_Click"/> <asp:Button ID="btnLast" runat="server" Text="Last >>" CommandArgument="Last" OnClick="pager_Click"/> </td> </tr> </table>
Code Behind
const int PAGE_SIZE = 10;
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
LoadGrid(1);
SetupPaging();
}
}
void LoadGrid(int pageNumber) {
Query q = new Query(Northwind.Tables.Product);
q.PageSize = 10;
q.PageIndex = pageNumber;
GridView1.DataSource = q.ExecuteDataSet();
GridView1.DataBind();
ResolvePagerView(pageNumber);
}
void SetupPaging() {
int pageCount = 0;
int totalRecords = 0;
//check to see if the totals have been set
if (lblPageCount.Text == string.Empty) {
totalRecords = new Query(Northwind.Tables.Product).GetCount(Northwind.Product.Columns.ProductID);
}
pageCount = totalRecords / PAGE_SIZE;
if (totalRecords % PAGE_SIZE > 0)
pageCount++;
lblPageCount.Text = pageCount.ToString();
//load up the list items
for (int i = 1; i <= pageCount; i++) {
ddlPages.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
}
void ResolvePagerView(int currentPage) {
int pageCount = 1;
int.TryParse(lblPageCount.Text, out pageCount);
int nextPage = currentPage + 1;
int prevPage = currentPage - 1;
btnPrev.Enabled = true;
btnNext.Enabled = true;
btnLast.Enabled = true;
btnFirst.Enabled = true;
if (currentPage == pageCount) {
btnNext.Enabled = false;
btnLast.Enabled = false;
} else if (currentPage == 1) {
btnPrev.Enabled = false;
btnFirst.Enabled = false;
}
}
protected void pager_Click(object sender, EventArgs e) {
Button btn = (Button)sender;
string pageCommand = btn.CommandArgument;
int currentPage = ddlPages.SelectedIndex + 1;
switch (pageCommand) {
case "First":
currentPage = 1;
break;
case "Prev":
currentPage--;
break;
case "Next":
currentPage++;
break;
case "Last":
currentPage = int.Parse(lblPageCount.Text);
break;
}
//reset the DropDown
ddlPages.SelectedValue = currentPage.ToString();
//reload the grid
LoadGrid(currentPage);
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e) {
//reload the grid
LoadGrid(ddlPages.SelectedIndex + 1);
}
