Recipe 2.9. Adding FirstLast Navigation to a DataGrid


Recipe 2.9. Adding First/Last Navigation to a DataGrid

Problem

You need to display data from a database in a table, but the database has more rows than will fit on a single page, and you want to use first/last buttons along with next/previous buttons for navigation.

Solution

Use a DataGrid control, add first/last and next/previous buttons (with event handlers for each one), and then bind the data to it.

In the .aspx file:

  1. Add a DataGrid control to the .aspx file.

  2. Add a row below the DataGrid with first/last and next/previous buttons for navigation.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Create a routine that binds a dataset to the DataGrid in the usual fashion.

  2. For each of the four buttons, create an event handler to handle the button's click event, perform the requisite page navigation, and rebind the data.

Figure 2-8 shows the appearance of a typical DataGrid within a browser with first/last and next/previous buttons for navigation. Examples 2-20, 2-21 through 2-22 show the .aspx and code-behind files for an application that produces this result.

Figure 2-8. DataGrid with first/last and next/previous navigation output


Discussion

The main theme of this recipe is to provide an alternative to the DataGrid control's default pagination controls and, at the same time, handle the custom paging. Setting the PagerStyle-Visible attribute to False makes the pager invisible in a DataGrid control, allowing you to implement your own user interface for the pagination controls. (The pager is the element on the DataGrid control that allows you to link to other pages when paging is enabled.) When the pager is invisible, some appearance-related attributes for the pager are not required and can be eliminated, specifically PagerStyle-Position, PagerStyle-HorizontalAlign, PagerStyle-NextPageText, and PagerStyle-PrevPageText. Adding a row below the DataGrid to hold the four navigation buttons (Next, Prev, First, and Last) is a key ingredient.

In the application we have developed for this recipe, we added four event handler routines to the code-behind to handle the click events for the four buttons, a handy strategy for your application as well. The event handlers alter the current page index for the grid (CurrentPageIndex), as appropriate, and rebind the data.

To improve performance, the event handlers check to see if the page needs changing and rebinding prior to changing the current page index value. For example, the btnPrev_ServerClick handler checks to see if CurrentPageIndex is greater than zero before subtracting one from it.

To improve performance still further, you could add the following code to the end of the bindData method to disable the appropriate buttons when no action would be taken on the server callfor example, disabling the First and Prev buttons when the first page is displayed. This would avoid an unnecessary trip to the server.

 Dim pageIndex as Integer = dgBooks.CurrentPageIndex If (pageIndex = 0) Then btnFirst.Disabled = True Else btnFirst.Disabled = False End If If (pageIndex = dgBooks.PageCount - 1) then btnLast.Disabled = True Else btnLast.Disabled = False End If 


See Also

Recipe 2.7 and the sidebar "Event Handlers" in Recipe 2.7

Example 2-20. DataGrid with first/last and next/previous navigation (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02DatagridWithFirstLastNavVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02DatagridWithFirstLastNavVB" Title="Datagrid With First/Last and Next/Prev Navigation" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > DataGrid With First/Last and Next/Previous Navigation (VB) </div> <asp:DataGrid  Runat="server"  BorderColor="#000080"  BorderWidth="2px"  AutoGenerateColumns="False"  Width="90%"  HorizontalAlign="Center"  AllowPaging="True"  PageSize="5"  PagerStyle-Visible="False"> <HeaderStyle HorizontalAlign="Center" Css /> <ItemStyle Css /> <AlternatingItemStyle Css /> <Columns> <asp:BoundColumn HeaderText="Title" DataField="Title" /> <asp:BoundColumn HeaderText="ISBN" DataField="ISBN" ItemStyle-HorizontalAlign="Center" /> <asp:BoundColumn HeaderText="Publisher" DataField="Publisher" ItemStyle-HorizontalAlign="Center" /> </Columns> </asp:DataGrid> <br /> <table width="40%" border="0" align="center"> <tr> <td align="center"> <input  runat="server" type="button" value="First" onserverclick="btnFirst_ServerClick"> </td> <td align="center"> <input  runat="server" type="button" value="Prev" onserverclick="btnPrev_ServerClick"> </td> <td align="center"> <input  runat="server" type="button" value="Next" onserverclick="btnNext_ServerClick"> </td> <td align="center"> <input  runat="server" type="button" value="Last" onserverclick="btnLast_ServerClick"> </td> </tr> </table> </asp:Content> 

Example 2-21. DataGrid with first/last and next/previous navigation code-behind (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02DatagridWithFirstLastNavVB.aspx ''' </summary> Partial Class CH02DatagridWithFirstLastNavVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If (Not Page.IsPostBack) Then bindData() End If End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the first button click ''' event. It is responsible for setting the page index to the first ''' page and rebinding the data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnFirst_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) 'set new page index and rebind the data If (dgBooks.CurrentPageIndex > 0) Then dgBooks.CurrentPageIndex = 0 bindData() End If End Sub 'btnFirst_ServerClick '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the previous button click ''' event. It is responsible for setting the page index to the previous ''' page and rebinding the data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnPrev_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) 'set new page index and rebind the data If (dgBooks.CurrentPageIndex > 0) Then dgBooks.CurrentPageIndex -= 1 bindData() End If End Sub 'btnPrev_ServerClick '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the next button click ''' event. It is responsible for setting the page index to the next ''' page and rebinding the data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnNext_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) 'set new page index and rebind the data If (dgBooks.CurrentPageIndex < dgBooks.PageCount - 1) Then dgBooks.CurrentPageIndex += 1 bindData() End If End Sub 'btnNext_ServerClick '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the last button click ''' event. It is responsible for setting the page index to the last ''' page and rebinding the data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnLast_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) 'set new page index and rebind the data If (dgBooks.CurrentPageIndex < dgBooks.PageCount - 1) Then dgBooks.CurrentPageIndex = dgBooks.PageCount - 1 bindData() End If End Sub 'btnLast_ServerClick '''*********************************************************************** ''' <summary> ''' This routine queries the database for the data to displayed and binds ''' it to the datagrid ''' </summary> Private Sub bindData() Dim dbConn As OleDbConnection = Nothing Dim da As OleDbDataAdapter = Nothing Dim dSet As DataSet = Nothing Dim strConnection As String Dim strSQL As String Try 'get the connection string from web.config and open a connection 'to the database strConnection = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dbConn = New OleDbConnection(strConnection) dbConn.Open() 'build the query string and get the data from the database strSQL = "SELECT Title, ISBN, Publisher " & _  "FROM Book " & _  "ORDER BY Title" da = New OleDbDataAdapter(strSQL, dbConn) dSet = New DataSet da.Fill(dSet) 'set the source of the data for the datagrid control and bind it dgBooks.DataSource = dSet dgBooks.DataBind() Finally 'cleanup If (Not IsNothing(dbConn)) Then dbConn.Close() End If  End Try End Sub 'bindData End Class 'CH02DatagridWithFirstLastNavVB End Namespace 

Example 2-22. DataGrid with first/last and next/previous navigation code-behind (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02DatagridWithFirstLastNavCS.aspx /// </summary> public partial class CH02DatagridWithFirstLastNavCS : System.Web.UI.Page { /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { bindData(); } } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the first button click /// event. It is responsible for setting the page index to the first /// page and rebinding the data. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnFirst_ServerClick(Object sender, System.EventArgs e) { // set new page index and rebind the data if (dgBooks.CurrentPageIndex > 0) { dgBooks.CurrentPageIndex = 0; bindData(); } } // btnFirst_ServerClick ///*********************************************************************** /// <summary> /// This routine provides the event handler for the previous button click /// event. It is responsible for setting the page index to the previous /// page and rebinding the data. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnPrev_ServerClick(Object sender, System.EventArgs e) { // set new page index and rebind the data if (dgBooks.CurrentPageIndex > 0) { dgBooks.CurrentPageIndex -= 1; bindData(); } } // btnPrev_ServerClick ///*********************************************************************** /// <summary> /// This routine provides the event handler for the next button click /// event. It is responsible for setting the page index to the next /// page and rebinding the data. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnNext_ServerClick(Object sender, System.EventArgs e) { // set new page index and rebind the data if (dgBooks.CurrentPageIndex < dgBooks.PageCount - 1) { dgBooks.CurrentPageIndex += 1; bindData(); } } // btnNext_ServerClick ///*********************************************************************** /// <summary> /// This routine provides the event handler for the last button click /// event. It is responsible for setting the page index to the last /// page and rebinding the data. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnLast_ServerClick(Object sender, System.EventArgs e) { // set new page index and rebind the data if (dgBooks.CurrentPageIndex < dgBooks.PageCount - 1) { dgBooks.CurrentPageIndex = dgBooks.PageCount - 1; bindData(); } } // btnLast_ServerClick ///*********************************************************************** /// <summary> /// This routine queries the database for the data to displayed and binds /// it to the datagrid /// </summary> private void bindData() { OleDbConnection dbConn = null; OleDbDataAdapter da = null; DataSet dSet = null; String strConnection; String strSQL; try { // get the connection string from web.config and open a connection  // to the database strConnection = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dbConn = new OleDbConnection(strConnection); dbConn.Open(); // build the query string and get the data from the database strSQL = "SELECT Title, ISBN, Publisher " +   "FROM Book " +   "ORDER BY Title"; da = new OleDbDataAdapter(strSQL, dbConn); dSet = new DataSet(); da.Fill(dSet); // set the source of the data for the datagrid control and bind it dgBooks.DataSource = dSet; dgBooks.DataBind(); } finally { // cleanup if (dbConn != null) { dbConn.Close(); } } } // bindData } // CH02DatagridWithFirstLastNavCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net