Recipe 2.10. Adding Direct Page Navigation to a DataGrid


Problem

You need to display data in a table, but the database that stores it has more rows than can fit on a single page, and you want to allow the user to select the page to display.

Solution

The simplest solution is to use a DataGrid control and its PagerStyle-Mode and PagerStyle-PageButton attributes to enable page selection. This approach produces output like that shown in Figure 2-9. To create an application that employs this approach, start by implementing Recipe 2.7 with the changes to the DataGrid tag shown here:

 PagerStyle-Mode="NumericPages" PagerStyle-PageButtonCount="5" 

Figure 2-9. Output of simple solution to DataGrid direct paging


A more flexible solution is to hide the pager provided by the DataGrid control and implement your own user interface for the pagination controls. This approach allows the user, for example, to input a page number in a text box and then click a button to display the data as shown in Figure 2-10. Examples 2-23, 2-24 through 2-25 show the .aspx and code-behind files for an application that produces this result.

Figure 2-10. Custom direct page navigation with a DataGrid output


Discussion

In the simple solution, setting the PagerStyle-Mode attribute to NumericPages causes the DataGrid to be rendered with page number buttons for navigating through the grid. The PagerStyle-ButtonCount attribute defines the number of "page buttons" that are output. If more pages are available than can be displayed, an ellipsis (…) is displayed at the end(s) of the page buttons containing additional pages. As shown in Figure 2-9, additional pages of data are available beyond Section 1.3. Clicking on the ellipsis will update the data in the DataGrid and display the next block of available pages for navigation. In our example, clicking on the ellipsis will cause Section 1.3.3 to be displayed in the DataGrid and Section 1.3.3, Section 1.3.4, Section 1.4, Section 1.4.2Section 1.4.4 will be available for direct navigation.

The more flexible solution enables paging in the grid but, with the code shown next, hides the pager provided by the DataGrid. Enabling pagination is required to have the DataGrid provide the infrastructure needed to perform the paging. Hiding the pager provides you with the ability to implement your own user interface for the pagination controls.

 AllowPaging="True" PageSize="5" PagerStyle-Visible="False"> 

The pagination controls provided in our example consist of a label to display the current page information, a text box to allow the user to enter the desired page number, and a button to initiate the page change. These controls are placed below the DataGrid in a row of the table containing the grid.

Like many of the previous examples in this chapter, the code-behind's bindData method queries the database to fill a DataSet. Additionally, with the following code, it updates the label used to display the "page x of y" information and to prompt the user to enter a page number.

 

lblPager.Text = "Displaying Page " & _ CStr(dgBooks.CurrentPageIndex + 1) & " of " & _ CStr(dgBooks.PageCount) & _ ", Enter Desired Page Number:"

lblPager.Text = "Displaying Page " + Convert.ToString(dgBooks.CurrentPageIndex + 1) + " of " + Convert.ToString(dgBooks.PageCount) + ", Enter Desired Page Number:";

The btnDisplayPage_Click method in the code-behind provides the server-side event handler for the button click event. This method retrieves from the text box the page number entered by the user and decrements it by 1, sets the CurrentPageIndex for the DataGrid, and rebinds the data. The page number must be decremented by 1 because the DataGrid pages are zero-based.

The pagination controls we provide here are simple. Almost any user interface can be constructed using HTML and tied into the DataGrid pagination functionality.

Production code should include validation of the page number entered by the user. This can be implemented using a RangeValidator control as described in Recipe 3.2.


See Also

Recipes 2.7 and 2.8 for implementing first/last and next/previous page navigation

Example 2-23. Custom direct page navigation with a DataGrid (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"  AutoEventWireup="false"  CodeFile="CH02DatagridWithDirectPageNavVB2.aspx.vb"  Inherits="ASPNetCookbook.VBExamples.CH02DatagridWithDirectPageNavVB2"  Title="DataGrid With Direct Page Navigation 2" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > DataGrid Using Custom Direct Page 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="70%" border="0" align="center"> <tr> <td> <asp:Label  Runat="server" Css /> </td> <td> <asp:TextBox  Runat="server" Width="40" /> </td> <td> <asp:Button  Runat="server"    Text="Update" OnClick="btnDisplayPage_Click" /> </td> </tr> </table> </asp:Content> 

Example 2-24. Custom direct page navigation with a DataGrid 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 ''' CH02DatagridWithDirectPageNavVB2.aspx ''' </summary> Partial Class CH02DatagridWithDirectPageNavVB2 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> Private 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 display page button ''' click event of the datagrid. It is responsible for setting the page ''' index to the entered 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 btnDisplayPage_Click(ByVal sender As Object, _    ByVal e As System.EventArgs) _ 'set new page index and rebind the data 'NOTE: The page numbers used by the datagrid control are 0 based '      so adjust the user enter page number to be 0 based dgBooks.CurrentPageIndex = CInt(txtNewPageNumber.Text) - 1 bindData() End Sub 'btnDisplayPage_Click '''*********************************************************************** ''' <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 OleDb.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() 'update label on custom pager to show current page and total pages lblPager.Text = "Displaying Page " & _ CStr(dgBooks.CurrentPageIndex + 1) & " of " & _ CStr(dgBooks.PageCount) & _ ", Enter Desired Page Number:" Finally 'cleanup If (Not IsNothing(dbConn)) Then dbConn.Close() End If  End Try    End Sub 'bindData  End Class 'CH02DatagridWithDirectPageNavVB2 End Namespace 

Example 2-25. Custom direct page navigation with a DataGrid 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  /// CH02DatagridWithDirectPageNavCS2.aspx  /// </summary>  public partial class CH02DatagridWithDirectPageNavCS2 : 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 display page button /// click event of the datagrid. It is responsible for setting the page /// index to the entered 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 btnDisplayPage_Click(Object sender,    System.EventArgs e) { // set new page index and rebind the data // NOTE: The page numbers used by the datagrid control are 0 based // so adjust the user enter page number to be 0 based dgBooks.CurrentPageIndex = Convert.ToInt32(txtNewPageNumber.Text) - 1; bindData(); } // btnDisplayPage_Click ///****************************************************************      /// <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(); //update label on custom pager to show current page and total pages lblPager.Text = "Displaying Page " +  Convert.ToString(dgBooks.CurrentPageIndex + 1) +  " of " + Convert.ToString(dgBooks.PageCount) +  ", Enter Desired Page Number:"; } finally { // cleanup if (dbConn != null) { dbConn.Close(); } } } // bindData  } // CH02DatagridWithDirectPageNavCS2 } 



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

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