The ASP.NET DataGrid

The ASP.NET DataGrid

So far, you've seen how to present data on Web pages with the Repeater and DataList controls. However, there are limitations to what you can present with these controls. For example, when there is too much data to display, the data control fills the Web Form beyond the viewable area of the browser, causing the user to scroll down the page to see data. Also, there is no built-in support for sorting the data in Repeaters and DataList controls. Fortunately, there is an ASP.NET data control that will perform sorting, paging, and other tasks for working with data, and it is called a DataGrid.

The most powerful of all ASP.NET data controls is the DataGrid. Like the DataList and Repeater controls, a DataGrid displays data with one record per row. However, a DataGrid enables you to display data with many more capabilities, such as paging, sorting, and editing. The example in this section demonstrates how to use a DataGrid with paging and sorting. Additionally, it will show how to filter data and how to use a DataView component. The next chapter, "XML Web Services," has an example that performs editing on a DataGrid control.

To set up the Web Form for this example, start a new ASP.NET project. Add a Button, a TextBox, and a DataGrid control to the Web Form from the Web Controls section of the Tools Palette. Set the Text property of the Button control to "Filter". The Button and TextBox controls should be positioned above the DataGrid. Finally, select the DataGrid on the Web Form designer, select the AutoFormat verb on the Object Inspector, select the Professional 2 scheme, and click the OK button to change the appearance of the DataGrid. Listing 16.9 is the Web Form that contains user interface controls for paging, filtering, and sorting a DataGrid.

Listing 16.9 HTML for a Web Form with a DataGrid Control (WebDataGrid.aspx)
 <?xml version="1.0"?> <%@ Page   language="c#"   Debug="true"   Codebehind="WebDataGrid.aspx.cs"   AutoEventWireup="false"   Inherits="WebDataGrid.WebDataGrid" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR"     content="Borland ASP.NET Designer for c# Package Library 7.1" />   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <asp:button  runat="server" text="Filter"></asp:button>       <asp:textbox  runat="server" width="339px"></asp:textbox>       <br />       <br />       <asp:datagrid  runat="server" allowpaging="True"       cellpadding="3" backcolor="White" bordercolor="#CCCCCC"       borderwidth="1px" borderstyle="None" allowsorting="True">         <footerstyle forecolor="#000066" backcolor="White"></footerstyle>         <headerstyle font-bold="True" forecolor="White" backcolor="#006699">         </headerstyle>         <pagerstyle horizontalalign="Left" forecolor="#000066"         position="TopAndBottom" backcolor="White"></pagerstyle>         <selecteditemstyle font-bold="True" forecolor="White"         backcolor="#669999"></selecteditemstyle>         <itemstyle forecolor="#000066"></itemstyle>       </asp:datagrid>     </form>   </body> </html> 

Listing 16.9 contains the HTML for the Web Form of the DataGrid example, and it contains a DataGrid control that was dragged-and-dropped from the Tool Palette. Notice that the asp:datagrid element contains allowpaging and allowsorting among its attributes and they are set to true, which are required to enable paging and sorting, respectively. The position attribute of the pagerstyle element specifies that paging controls will appear at the top and bottom of the DataGrid control. Also, there are Button and TextBox controls on the Web Form that will be used for filtering.

To set the paging and sorting attributes, select the DataGrid control in the Web Form designer and select the Property Builder verb in the Object Inspector. In the dataGrid1 Properties dialog, select General, check Allow Sorting, and uncheck Show Footer. Then select Paging, check Allow Paging, and select Next, Previous buttons from the Mode control. When you're done, the HTML for the Web Form should look like that in Listing 16.9.

The next step is to modify the code-behind file, which is shown in Listing 16.10.

Listing 16.10 Code-Behind for Binding to a DataGrid Control (WebDataGrid.aspx.cs)
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebDataGrid {    public class WebDataGrid : System.Web.UI.Page    {       protected System.Web.UI.WebControls.DataGrid dataGrid1;       protected Borland.Data.Provider.BdpConnection bdpConnection1;       protected Borland.Data.Provider.BdpDataAdapter bdpDataAdapter1;       protected Borland.Data.Provider.BdpCommand bdpSelectCommand1;       protected Borland.Data.Provider.BdpCommand bdpInsertCommand1;       protected Borland.Data.Provider.BdpCommand bdpUpdateCommand1;       protected Borland.Data.Provider.BdpCommand bdpDeleteCommand1;       protected System.Data.DataSet dataSet1;       protected System.Data.DataTable Table1;       protected System.Data.DataColumn dataColumn1;       protected System.Data.DataColumn dataColumn2;       protected System.Data.DataColumn dataColumn3;       protected System.Web.UI.WebControls.TextBox textBox1;       protected System.Web.UI.WebControls.Button button1;       private void Page_Load(object sender, System.EventArgs e)       {          if (Session["SortExpression"] == null)          {             Session["SortExpression"] = "ProductName";          }          if (!IsPostBack)          {             BindGrid();          }       }       private void BindGrid()       {          DataView sortedView = new DataView(             Table1,             (string)Session["FilterExpression"],             (string)Session["SortExpression"],             DataViewRowState.OriginalRows);          dataGrid1.DataSource = sortedView;          dataGrid1.DataBind();       }       #region Web Form Designer generated code       override protected void OnInit(EventArgs e)       {          //          // CODEGEN: This call is required by the ASP.NET Web Form Designer.          //          InitializeComponent();          base.OnInit(e);       }       /// <summary>       /// Required method for Designer support - do not modify       /// the contents of this method with the code editor.       /// </summary>       private void InitializeComponent()       {          // auto-generated code removed       }       #endregion       private void dataGrid1_SortCommand(          object source,          System.Web.UI.WebControls.DataGridSortCommandEventArgs e)       {          Session["SortExpression"] = e.SortExpression;          BindGrid();       }       private void dataGrid1_PageIndexChanged(          object source,          System.Web.UI.WebControls.DataGridPageChangedEventArgs e)       {          dataGrid1.CurrentPageIndex = e.NewPageIndex;          BindGrid();       }       private void button1_Click(object sender, System.EventArgs e)       {          Session["FilterExpression"] = textBox1.Text;          BindGrid();       }    } } 

Listing 16.10 contains the code-behind file for implementing the paging, filtering, and sorting capability in the DataGrid. Because all event handlers in this file call the BindGrid method, let's look at it first. The BindGrid method first creates a new instance of the DataView class. Previous examples showed how to bind a DataTable directly to the Repeater and DataList controls, but this example will use a DataView instead. Generally, the purpose of a DataView is to provide a customized view of a table as a DataSource to a bindable control. For this example, we will use a DataView to provide both filtering and sorting support. The DataView is bound to the DataGrid DataSource property, in the same manner as when the DataTable was bound to the Repeater and DataList controls.

The DataView in the BindGrid method is instantiated with four parameters. The first parameter is the DataTable to use. The second parameter is a string that specifies the filter, and the third parameter is a string that specifies the column name to sort. Both the filter and sort parameters are derived from session state, which is set in event handler methods in the same code-behind file. The last parameter is a DataViewRowState enum, which identifies what type of records may appear. In this case it shows all rows with the OriginalRows member. The .NET Framework SDK documentation contains definitions for other row types that may be filtered, such as those that are added, deleted, or modified.

The DataGrid control has SortCommand and PageIndexChanged events, which I hooked up through the Events tab of the Object Inspector. Because I set the DataGrid to allow sorting, when the user clicks on the column head of the DataGrid during runtime, the Web Form will post back and the SortCommand event will fire. The event handler will extract the SortExpression from the DataGridSortCommandEventArgs parameter and store it into session state. Then it will call BindGrid, which customizes the data and rebinds the data to the DataGrid.

When the user clicks on a page change link, the Web Form will post back and fire the DataGrid PageIndexChanged event. The dataGrid1_PageIndexChanged event handler will extract the NewPageIndex property from the DataGridPageIndexChangedEventArgs parameter and assign it to the CurrentPageIndex property of the DataGrid. This sets the page that the DataGrid should display. Then it will call BindGrid, which customizes the data and rebinds the data to the DataGrid.

When setting up this Web Form, I also created a Click event handler for the filter button. When the filter button is clicked by the user, the Web Form will post back and fire the Clicked event of the button. The button1_Click event handler will read the value from the TextBox and store it in session state. Then it will call BindGrid to customize the data and rebind to the DataGrid.

Unlike paging and sorting, filtering is not something unique to a DataGrid. It is a capability of the DataView that was implemented by a custom event handler. The filter you use should be something that would normally fit into a SQL where clause. For example, ProductName like 'Ch%' would display only those records where the ProductName column value began with the letters Ch, and UnitPrice > 20 would display only those records where the UnitPrice column value was greater than 20.

See Figure 16.12 to view this Web Form as it is executing. Chapter 17, "XML Web Services," shows more ways to use the DataGrid control, with editing, deleting, inserting, and updating records.

Figure 16.12. A Web Form with the ASP.NET DataGrid control.

graphics/16fig12.jpg



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

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