Recipe 2.8. Adding NextPrevious Navigation to a DataGrid


Recipe 2.8. Adding Next/Previous Navigation to a DataGrid

Problem

You need to display data from a database in a table; the database has more rows than can fit on a single page, so you want to use next/previous buttons for navigation.

Solution

Use a DataGrid control, enable its built-in pagination features, and then bind the data to it.

Add a DataGrid control to the .aspx file, and use its AllowPaging and other related attributes to enable pagination.

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. Create an event handler that performs the page navigation, for example, one that handles the PageIndexChanged event for the DataGrid and rebinds the data.

Figure 2-6 shows the appearance of a typical DataGrid within a browser with next/previous navigation. Examples 2-17, 2-18 through 2-19 show the .aspx and code-behind files for an application that produces this result.

Figure 2-6. DataGrid with next/previous navigation output


Discussion

The DataGrid control includes the ability to perform pagination of the data that is displayed in the grid; using the built-in pagination requires little code. Pagination is enabled and configured by the attributes of the DataGrid element:

 AllowPaging="True" PageSize="5" PagerStyle-Mode="NextPrev" PagerStyle-Position="Bottom" PagerStyle-HorizontalAlign="Center" PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev" 

Setting the AllowPaging attribute to TRue enables paging for the DataGrid, and the PageSize attribute defines the number of rows that will be displayed in a single page. Setting the PageStyle-Mode attribute to NextPrev enables the output of the Next/Prev controls (see Recipe 2.9 for other uses of this attribute).

The remaining attributes define how the pagination controls look. PagerStyle-Position defines the location of the Next/Prev controls. Valid values include Bottom, Top, and TopAndBottom. PagerStyle-HorizontalAlign defines the horizontal positioning of the Next/Prev controls. Valid values include Left, Center, Right, and NotSet. NotSet is effectively the same as Left because Left is the default.

PagerStyle-NextPageText defines the text to output for the next page navigation control, and PagerStyle-PrevPageText defines the text to output for the previous page navigation.

The PagerStyle-NextPageText and PagerStyle-PrevPageText attribute values can include HTML to format the text of the controls. Almost any HTML can be used, including image tags. If you change the values of the two text attributes, the Next/Prev controls will be output as shown in Figure 2-7.

 PagerStyle-NextPageText= "<img src='/books/1/505/1/html/2/images/button_next.gif' border='0'>" PagerStyle-PrevPageText= "<img src='/books/1/505/1/html/2/images/button_prev.gif' border='0'>"> 


Figure 2-7. DataGrid output using image tags for next/previous controls


The bindData routine, shown in the code-behind in Examples 2-18 (VB) and 2-19 (C#), performs the data binding. This routine provides the typical binding of a dataset to the DataGrid. No additional code is required in this routine to support the default pagination.

The SqlDataSource and ObjectDataSource data source controls provided in ASP.NET 2.0 cannot be used with a DataGrid when paging is implemented. The DataGrid requires its data source to implement ICollection to support paging. The ICollection interface is not implemented by the new data source controls. Using a data source control with a DataGrid when pagination is implemented will result in an exception such as the following being thrown:

AllowCustomPaging must be TRue and VirtualItemCount must be set for a DataGrid with ID "dgBooks" when AllowPaging is set to true and the selected data source does not implement ICollection.


The dgBooks_PageIndexChanged event handler provides the code required to perform the page navigation. The new page number to display is passed in the event arguments (e). The CurrentPageIndex property of the DataGrid must be set to the passed value, and the data must be rebound to the DataGrid.

The default pagination code shown in this recipe can be inefficient when used with data containing a large number of rows. By default, all of the data for a query is returned and used to populate the DataSet. When the query returns a small set of data (fewer than 100 rows and a small number of columns), the pagination shown in this recipe is adequate for most applications. If your query returns a million rows, the performance of your application will be unacceptable. See Recipe 2.12 for a more efficient approach to the pagination of large datasets.


Event Handlers

The method used to connect event handlers to events in Version 1.x of ASP.NET was implemented in different ways for VB and C#. VB required two additions to your code to handle an event. First, the control that had events to handle needed to be declared in the code-behind class using the WithEvents keyword as shown here:

 Protected WithEvents dgBooks As DataGrid 

Second, the method used to handle an event needed to have the Handles keyword added to the end of the method and include the control and event to be handled. This informed the compiler to add the code required to "wire" the event to the method.

 Private Sub dgBooks_PageIndexChanged(ByVal source As Object, ByVal e As DataGridPageChangedEventArgs) Handles dgBooks.PageIndexChanged 

In C#, events were connected to methods by explicitly creating a new event handler of the required type and "wiring" it to the desired control's event:

 this.dgBooks.PageIndexChanged += new DataGridPageChangedEventHandler (this.dgBooks_PageIndexChanged); 

Version 2.0 of ASP.NET has implemented a simpler and more consistent method of connecting event handlers to events. Server controls now have new attributes to define the server-side event handlers to be called when a specific event occurs. For example, the DataGrid has an OnPageIndexChanged attribute used in this recipe to connect the OnPageIndexChanged event to the dgBooks_PageIndexChanged event handler in the code-behind class:

 <asp:DataGrid runat="server" … OnPageIndexChanged="dgBooks_PageIndexChanged" > … </asp:DataGrid> 

To provide backward compatibility, the approach used in Version 1.x can be used in Version 2.0.


See Also

Recipes 2.8, 2.9, and 2.12 for other examples of pagination

Example 2-17. DataGrid with next/previous navigation (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"  AutoEventWireup="false"  CodeFile="CH02DatagridWithNextPrevNavVB1.aspx.vb"  Inherits="ASPNetCookbook.VBExamples.CH02DatagridWithNextPrevNavVB1"  Title="Datagrid With Text For Next/Prev Navigation" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > DataGrid Using Text For Next/Previous Navigation (VB) </div> <asp:DataGrid runat="server" BorderColor="000080" BorderWidth="2px" AutoGenerateColumns="False" HorizontalAlign="Center" Width="90%" AllowPaging="True" PageSize="5" PagerStyle-Mode="NextPrev" PagerStyle-Position="Bottom" PagerStyle-HorizontalAlign="Center" PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev" OnPageIndexChanged="dgBooks_PageIndexChanged" > <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> </asp:Content> 

Example 2-18. DataGrid with 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 ''' CH02DatagridWithNextPrevNavVB1.aspx ''' </summary> Partial Class CH02DatagridWithNextPrevNavVB1 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 page index changed ''' event of the datagrid. It is responsible for setting the page index ''' from the passed arguments and rebinding the data. ''' </summary> ''' ''' <param name="source">Set to the source of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub dgBooks_PageIndexChanged(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) 'set new page index and rebind the data dgBooks.CurrentPageIndex = e.NewPageIndex bindData() End Sub 'dgBooks_PageIndexChanged '''*********************************************************************** ''' <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 'CH02DatagridWithNextPrevNavVB1 End Namespace 

Example 2-19. DataGrid with 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  /// CH02DatagridWithNextPrevNavCS1.aspx  /// </summary>  public partial class CH02DatagridWithNextPrevNavCS1 : 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 page index changed /// event of the datagrid. It is responsible for setting the page index /// from the passed arguments and rebinding the data. /// </summary> /// /// <param name="source">Set to the source of the event</param> /// <param name="e">Set to the event arguments</param> protected void dgBooks_PageIndexChanged(Object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) { // set new page index and rebind the data dgBooks.CurrentPageIndex = e.NewPageIndex; bindData(); } // dgBooks_PageIndexChanged ///*********************************************************************** /// <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 } // CH02DatagridWithNextPrevNavCS1  } 



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