DataGrid .NET Server Control

DataGrid .NET Server Control"-->

only for RuBoard

DataGrid .NET Server Control

The DataGrid control is a multicolumn, data-bound (bound to a data source ”an object that supports an ICollection interface ” ArrayList , DataView ) grid that displays data in a tabular fashion (rows and columns ). In order for the DataGrid to render any HTML elements to the page, the DataGrid must be bound to a data source that supports this interface ” ICollection . When the DataGrid is rendered to a web form, an HTML table is created ( <table> ). As you probably are aware an HTML table has four parts :

  • Table Header ” The top row in the table.

  • Table Row ” Spans the width of the table, containing one or more columns.

  • Table Column ” Spans the height of the table, containing one or more rows.

  • Table Footer ” The last row in the table.

The DataGrid has a set of intrinsic features that gives you access to which columns are rendered from its data source and in what order. By default the DataGrid is rendered automatically based on the structure of its data source. For instance, if the DataGrid.DataSource is a DataTable that has four fields and 20 rows, the DataGrid will render a table that has a header with the value of each field name from the data source, four columns (one for each field in the data source), and 20 rows (one for each row in the data source). Each cell will contain the value of the row and field for that record in the data source.

You can override this default behavior by using column objects. Using column objects enables you to manipulate both the style and content of your DataGrid column-by-column. The following list contains all the different column objects available when using the DataGrid :

  • BoundColumn ” Enables you to specify a particular field from your data source to bind to. A BoundColumn also enables you to specify the style and format of the data displayed.

  • HyperLinkColumn ” Enables you to specify a particular field from your data source to bind to and displays the data in the column as a hyperlink ( <a href="">DataItem</a> ).

  • ButtonColumn ” Renders a Button control for each item (row) in your data source. You can either manually set its Text attribute or bind it to a field from your data source.

  • EditCommandColumn ” Enables you to create editing features for your DataGrid. Buttons for putting the DataGrid into different modes (edit) are rendered for each item (row) in your data source. (Editing is covered in Chapter 10.)

  • TemplateColumn ” Gives you precise control over what is rendered by the DataGrid . You can create combinations of HTML and server controls and design a custom layout for a column.

The most powerful entry in this list is the TemplateColumn . The TemplateColumn supports the following templates within it:

  • HeaderTemplate ” Defines how the columns header is rendered.

  • FooterTemplate ” Defines how the columns footer is rendered.

  • ItemTemplate ” Defines how items are rendered within the column.

  • EditItemTemplate ” Defines how items in Edit Mode are rendered within the columns.

In the following sections, first I'll go over using the basic DataGrid . Second, I'll go over how to use the column objects in the DataGrid (ex: BoundColumn ). Finally, I'll go over how to use template columns with the DataGrid .

The Basic DataGrid

As you'll remember from previous chapters, the basic DataGrid is very easy to implement and can be done in as little as one line of code. Listing 7.1 demonstrates how to use some of DataGrid 's inherent attributes to improve the way the DataGrid looks when it's rendered to the page.

Listing 7.1 Code to Render a Simple DataGrid to a Web Form
 [VisualBasic.NET] 01: <%@ Import Namespace="System.Data" %> 02: <%@ Import Namespace="System.Data.SqlClient" %> 03: 04: <script language="VB" runat="server"> 05: 06:  sub Page_Load(sender as Object, e as EventArgs) 07: 08:   dim SqlCmd as new StringBuilder() 09:   SqlCmd.Append("SELECT S.CompanyName [Company Name],") 10:   SqlCmd.Append("P.ProductName [Product Name],") 11:   SqlCmd.Append("P.QuantityPerUnit [Quantity Per Unit],") 12:   SqlCmd.Append("P.UnitPrice [Unit Price],") 13:   SqlCmd.Append("P.UnitsInStock [Units In Stock],") 14:   SqlCmd.Append("P.UnitsOnOrder [Units On Order] ") 15:   SqlCmd.Append("FROM Products P ") 16:   SqlCmd.Append("INNER JOIN Suppliers S ") 17:   SqlCmd.Append("ON ") 18:   SqlCmd.Append("S.SupplierID = P.SupplierID") 19: 20:   dim SqlCon as new SqlConnection("server=localhost; graphics/ccc.gif uid=sa;pwd=;database=northwind") 21:   dim sqlcommand as new SqlCommand(SqlCmd.ToString(), SqlCon) 22: 23:   SqlCon.Open() 24:    MyDataGrid.DataSource = sqlcommand.ExecuteReader() 25:    MyDataGrid.DataBind() 26:   SqlCon.Close() 27: 28: End Sub 29: 30: </script> [C#.NET] 01: <%@ Import Namespace="System.Data" %> 02: <%@ Import Namespace="System.Data.SqlClient" %> 03: 04: <script language="c#" runat="server"> 05: 06:  public void Page_Load(Object sender, EventArgs e) { 07: 08:   StringBuilder SqlCmd = new StringBuilder(); 09:   SqlCmd.Append("SELECT S.CompanyName [Company Name],"); 10:   SqlCmd.Append("P.ProductName [Product Name],"); 11:   SqlCmd.Append("P.QuantityPerUnit [Quantity Per Unit],"); 12:   SqlCmd.Append("P.UnitPrice [Unit Price],"); 13:   SqlCmd.Append("P.UnitsInStock [Units In Stock],"); 14:   SqlCmd.Append("P.UnitsOnOrder [Units On Order] "); 15:   SqlCmd.Append("FROM Products P "); 16:   SqlCmd.Append("INNER JOIN Suppliers S "); 17:   SqlCmd.Append("ON "); 18:   SqlCmd.Append("S.SupplierID = P.SupplierID"); 19: 20:   SqlConnection SqlCon = new SqlConnection("server=localhost; graphics/ccc.gif uid=sa;pwd=;database=northwind"); 21:   SqlCommand sqlcommand = new SqlCommand(SqlCmd.ToString(), SqlCon); 22: 23:   SqlCon.Open(); 24:    MyDataGrid.DataSource = sqlcommand.ExecuteReader(); 25:    MyDataGrid.DataBind(); 26:   SqlCon.Close(); 27: 28: } 29: 30: </script> [VisualBasic.NET & C#.NET] 31: <html> 32: <head><title>DotNetJunkies.com</title></head> 33: <body> 34:        <asp:DataGrid 35:         id="MyDataGrid" 36:         runat="server" 37:         AutoGenerateColumns="True" 38:         GridLines="Vertical" 39:         Width="100%" 40:         CellPadding="4" 41:         CellSpacing="0" 42: 43:         HeaderStyle-BackColor="maroon" 44:         HeaderStyle-ForeColor="#FFFFFF" 45:         HeaderStyle-Font-Size="10" 46:         HeaderStyle-Font-Bold="true" 47:         HeaderStyle-Font-Name="Verdana" 48: 49:         ItemStyle-BackColor="Green" 50:         ItemStyle-ForeColor="White" 51:         ItemStyle-Font-Size="8" 52:         ItemStyle-Font-Bold="true" 53:         ItemStyle-Font-Name="Verdana" 54: 55:         AlternatingItemStyle-BackColor="White" 56:         AlternatingItemStyle-ForeColor="Black" 57:         AlternatingItemStyle-Font-Size="8" 58:         AlternatingItemStyle-Font-Bold="true" 59:         AlternatingItemStyle-Font-Name="Verdana" 60: 61:         /> 62: </body> 63: </html> 

In Listing 7.1, fields from both the Supplier and the Products table are returned from the SQL query. Within the SQL statement I gave the field names human-readable names because in this type of DataGrid the header text will be populated from the field names in its DataGrid.DataSource . For example, if I didn't change the names in the SQL statement, the first column of the DataGrid would be called CompanyName instead of Company Name (line 9).

As previously mentioned this DataGrid is in one of its most basic forms. However, I did use some of its attributes to improve on its looks (lines 43-59). On line 37 the AutoGenerateColumns attribute is set to True . This means that each column will be automatically generated for the DataGrid based on its data source, one column for each field. In this example, if this value were false nothing would render to the client. Figure 7.1 contains an illustration of this page when rendered. Notice the header text and its enhanced appearance.

Figure 7.1. The basic DataGrid .
graphics/07fig01.gif

Getting More Control Using Column Objects

As previously mentioned, the DataGrid enables you to control which fields from your data source to display, and how to display them, by using column objects. There are a total of five different column objects, as listed in the "DataGrid .NET Server Control" section earlier in the chapter. This section covers BoundColumn and HyperlinkColumn . The ButtonColumn will be discussed in Chapter 10, "Inputting and Editing Data with the DataGrid."

Listing 7.2 contains the code example illustrating how to use these two types of column objects. The server code used in this example is very similar to that of Listing 7.1, but you'll notice that we don't rename the fields from our database from within the SQL statement. Instead, we use the column objects HeaderText attribute.

Listing 7.2 Code for DataGrid Using Column Objects
 [VisualBasic.NET] 01: <%@ Import Namespace="System.Data" %> 02: <%@ Import Namespace="System.Data.SqlClient" %> 03: 04: <script language="VB" runat="server"> 05: 06:  sub Page_Load(sender as Object, e as EventArgs) 07: 08:   dim SqlCmd as new StringBuilder() 09:   SqlCmd.Append("SELECT S.CompanyName,") 10:   SqlCmd.Append("P.ProductName,") 11:   SqlCmd.Append("P.QuantityPerUnit,") 12:   SqlCmd.Append("P.UnitPrice,") 13:   SqlCmd.Append("P.UnitsInStock,") 14:   SqlCmd.Append("P.UnitsOnOrder ") 15:   SqlCmd.Append("FROM Products P ") 16:   SqlCmd.Append("INNER JOIN Suppliers S ") 17:   SqlCmd.Append("ON ") 18:   SqlCmd.Append("S.SupplierID = P.SupplierID") 19: 20:   dim SqlCon as new SqlConnection("server=localhost; graphics/ccc.gif uid=sa;pwd=;database=northwind") 21:   dim sqlcommand as new SqlCommand(SqlCmd.ToString(), SqlCon) 22: 23:   SqlCon.Open() 24:    MyDataGrid.DataSource = sqlcommand.ExecuteReader() 25:    MyDataGrid.DataBind() 26:   SqlCon.Close() 27: 28: End Sub 29: 30: </script> [C#.NET] 01: <%@ Import Namespace="System.Data" %> 02: <%@ Import Namespace="System.Data.SqlClient" %> 03: 04: <script language="c#" runat="server"> 05: 06:  public void Page_Load(Object sender, EventArgs e) { 07: 08:   StringBuilder SqlCmd = new StringBuilder(); 09:   SqlCmd.Append("SELECT S.CompanyName,"); 10:   SqlCmd.Append("P.ProductName,"); 11:   SqlCmd.Append("P.QuantityPerUnit,"); 12:   SqlCmd.Append("P.UnitPrice,"); 13:   SqlCmd.Append("P.UnitsInStock,"); 14:   SqlCmd.Append("P.UnitsOnOrder "); 15:   SqlCmd.Append("FROM Products P "); 16:   SqlCmd.Append("INNER JOIN Suppliers S "); 17:   SqlCmd.Append("ON "); 18:   SqlCmd.Append("S.SupplierID = P.SupplierID"); 19: 20:   SqlConnection SqlCon = new SqlConnection("server=localhost; graphics/ccc.gif uid=sa;pwd=;database=northwind"); 21:   SqlCommand sqlcommand = new SqlCommand(SqlCmd.ToString(), SqlCon); 22: 23:   SqlCon.Open(); 24:    MyDataGrid.DataSource = sqlcommand.ExecuteReader(); 25:    MyDataGrid.DataBind(); 26:   SqlCon.Close(); 27: 28: } 29: 30: </script> [VisualBasic.NET & C#.NET] 31: <html> 32: <head><title>DotNetJunkies.com</title> 33: <style rel="stylesheet"> 34: 35:  A { text-decoration:none;color:black} 36:  A:Hover { color:maroon;text-decoration:underline} 37:  A:Visited { color:red} 38: 39: </style> 40: </head> 41: <body> 42:         <asp:DataGrid 43:         id="MyDataGrid" 44:         runat="server" 45:         AutoGenerateColumns="False" 46:         GridLines="Both" 47:         Width="100%" 48:         CellPadding="4" 49:         CellSpacing="0" 50:         > 51: 52:         <columns> 53: 54:          <asp:BoundColumn 55:           DataField="CompanyName" 56:           HeaderText="Company Name" 57:           HeaderStyle-BackColor="maroon" 58:           HeaderStyle-ForeColor="#FFFFFF" 59:           HeaderStyle-Font-Size="10" 60:           HeaderStyle-Font-Bold="true" 61:           HeaderStyle-Font-Name="Verdana" 62: 63:           ItemStyle-BackColor="#FFFFFF" 64:           ItemStyle-ForeColor="#000000" 65:           ItemStyle-Font-Size="8" 66:           ItemStyle-Font-Bold="true" 67:           ItemStyle-Font-Name="Verdana" 68: 69:           /> 70: 71:          <asp:BoundColumn 72:           DataField="ProductName" 73:           HeaderText="Product Name" 74: 75:           HeaderStyle-BackColor="maroon" 76:           HeaderStyle-ForeColor="#FFFFFF" 77:           HeaderStyle-Font-Size="10" 78:           HeaderStyle-Font-Bold="true" 79:           HeaderStyle-Font-Name="Verdana" 80: 81:           ItemStyle-BackColor="#FFFFFF" 82:           ItemStyle-ForeColor="#000000" 83:           ItemStyle-Font-Size="8" 84:           ItemStyle-Font-Bold="true" 85:           ItemStyle-Font-Name="Verdana" 86: 87:           /> 88: 89:          <asp:BoundColumn 90:           DataField="UnitPrice" 91:           HeaderText="Price Per Unit" 92:           DataFormatString="{ 0:C} " 93: 94:           HeaderStyle-BackColor="maroon" 96:           HeaderStyle-ForeColor="#FFFFFF" 97:           HeaderStyle-Font-Size="10" 98:           HeaderStyle-Font-Bold="true" 99:           HeaderStyle-Font-Name="Verdana" 100: 101:           ItemStyle-BackColor="#FFFFFF" 102:           ItemStyle-ForeColor="#000000" 103:           ItemStyle-Font-Size="8" 104:           ItemStyle-Font-Bold="true" 105:           ItemStyle-Font-Name="Verdana" 106: 107:           /> 108: 109:          <asp:HyperLinkColumn 110:           Text="Click Here" 111:           HeaderText="More Info" 112:           DataNavigateUrlField="ProductName" 113:           DataNavigateUrlFormatString=   "ProductDetails.aspx?ProductName={ 0} " 114:           Target="_blank" 115: 116:           HeaderStyle-BackColor="maroon" 117:           HeaderStyle-ForeColor="#FFFFFF" 118:           HeaderStyle-Font-Size="10" 119:           HeaderStyle-Font-Bold="true" 120:           HeaderStyle-Font-Name="Verdana" 121: 122:           ItemStyle-BackColor="#FFFFFF" 123:           ItemStyle-ForeColor="White" 124:           ItemStyle-Font-Size="8" 125:           ItemStyle-Font-Bold="true" 126:           ItemStyle-Font-Name="Verdana" 127: 128:           /> 129: 130:         </columns> 131: 132:         </asp:DataGrid> 133: </body> 134: </html> 

Beginning with the starting DataGrid tag (line 42) let's walk through the DataGrid code from Listing 7.2. The first thing you might have noticed is I changed the value of the AutoGenerateColumns attribute from true to false . The reason I did this is because when it is set to true the DataGrid will render a column for each field in the DataGrid.DataSource even when using column objects. Hence, if the value were true for this example, there would be 10 columns rendered ”the 6 default fields from the data source and the 4 from the bound columns.

There are a total of 4 column objects used in this example. There are three BoundColumns and one HyperLinkColumn . The three BoundColumns are located in lines 54 “107. You'll notice that I set their style attributes within their individual tags. This gives you greater control on how the columns appear when rendered because one column BackColor can be different than another.

You also have complete control on which fields from the data source are displayed when using column objects and where within the DataGridColumnCollection they'll be shown. In this example only 3 out of the 6 fields are displayed from the DataGrid.DataSource . Additionally, you can also use one field more than once as I did in this example by using the ProductName field value for both a BoundColumn and the HyperLinkColumn .

Displaying data within a BoundColumn is quite simple. You use the DataField attribute to set the field from the data source you wish to display in that column and the HeaderText attribute to set the Header for the column. For instance, in the first BoundColumn starting on line 54 the DataField is set to be the CompanyName field value (line 55) from the DataGrid.DataSource and the HeaderText is set to " Company Name " ”a hard coded, static value.

Displaying data within the HyperLinkColumn is quite different than the BoundColumn . The reason is that it doesn't necessarily have to bind to any field from the data source; but even if not bound to a field, the HyperLinkColumn will still be rendered once for each row in the data source. In this example it is bound to a field, the ProductName field. I use the HyperLinkColumn.DataNavigateUrlField attribute to bind the HyperLinkColumn to the ProductName field (line 112) and the HyperLinkColumn.DataNavigateUrlFormatString (line 113) to access the value and append it to a URL as a parameter value. On line 110 I use its Text attribute to set the text rendered for each row to a static value Click Here . Alternatively, you can use the DataTextField attribute to bind the text displayed to a field in its data source. Some additional attributes can be found in the following list:

  • HyperLinkColumn.NavigateUrl The value is a static URL that should be navigated to when clicked on. You cannot have both this and DataNavigateUrlField attributes set at the same time.

  • HyperLinkColumn.Target Used to get or set the "target" window or frame to display the page being navigated to (ex: Target="_blank" ).

Figure 7.2. The DataGrid using column objects.
graphics/07fig02.gif

The Ultimate Control: Template Columns

For the ultimate control over what is rendered in each column you can use the TemplateColumn . This enables you to add any type of HTML elements or server controls to the DataGrid and control which fields are shown and where. Using the same server code from Listing 7.2 replace the code between the starting <html> and ending </html> tags with the code example found in Listing 7.3.

Listing 7.3 Using a Template Column in the DataGrid
 [VisualBasic.NET and C#.NET] 31: <html> 32: <head><title>DotNetJunkies.com</title> 33: <style rel="stylesheet"> 34: 35:  A { text-decoration:none;color:black} 36:  A:Hover { color:maroon;text-decoration:underline} 37:  A:Visited { color:red} 38:  .body {  font: 9pt Verdana, Arial, sans-serif; } 39:  .head {  font: bold 9pt Verdana, Arial,   sans-serif; background-color:Maroon; color: graphics/ccc.gif white; } 40:  .tablehead {  font: bold 9pt Verdana, Arial,   sans-serif; background-color:green; graphics/ccc.gif color:white; } 41: </style> 42: </head> 43: <body> 44:  <center> 45:   <asp:DataGrid 46:   id="MyDataGrid" 47:   runat="server" 48:   AutoGenerateColumns="False" 49:   GridLines="Both" 50:   Width="500" 52:   CellSpacing="0" 53:   > 54: 55:    <columns> 56: 57:     <asp:TemplateColumn 58:     HeaderStyle-CssClass="head" 59:     ItemStyle-CssClass="body" 60:     > 61: 62:      <HeaderTemplate> 63:      <center>Northwind Products</center> 64:      </HeaderTemplate> 65: 66:      <ItemTemplate> 67:       <table width="100%"> 68:        <tr> 69:         <td align="center" class="tablehead" ColSpan="2"> 70:          <%# DataBinder.Eval(Container.DataItem, "ProductName" )%> 71:         </td> 72:        </tr> 73:        <tr> 74:         <td class="body" align="left" valign="top"> 75:          <b>Price</b> 76:         </td> 77:         <td class="body" align="right" valign="top"> 78:          <b><%# DataBinder.Eval(   Container.DataItem, "UnitPrice",  "{ 0:C} ")%></b> 79:         </td> 80:        </tr> 81:        <tr> 82:         <td class="body" align="left" valign="top"> 83:          <b>Quantity Per Unit</b> 84:         </td> 85:         <td class="body" align="right" valign="top"> 86:          <b><%# DataBinder.Eval(   Container.DataItem, "QuantityPerUnit")%></b> 87:         </td> 88:        </tr> 89:        <tr> 90:         <td align="center" class="head" ColSpan="2"></td> 91:        </tr> 92:        <tr> 93:         <td class="body" ColSpan="2" align="center"> 94:          <a Target="_blank" 95:          href="ProductDetails.aspx?ProductName=<%# DataBinder.Eval( graphics/ccc.gif Container.DataItem, "ProductName")%>"> 96:          [ More Information Click Here ] 97:          </a> 98:         </td> 99:        </tr> 100:       </table> 101:      </ItemTemplate> 102: 103:     </asp:TemplateColumn> 104: 105:    </columns> 106: 107:   </asp:DataGrid> 108:  </center> 109: </body> 110: </html> 

As previously mentioned there are four parts to the TemplateColumn :

  • HeaderTemplate ” The HTML or text that should be rendered for the Header

  • FooterTemplate ” The HTML or text that should be rendered for the Footer

  • ItemTemplate ” The HTML or text that should be rendered for each item

  • EditItemTemplate ” The HTML or text that should be rendered when the DataGrid is in "edit mode"

In this example I used only the HeaderTemplate (lines 62 “64) and the ItemTemplate (lines 66 “101) and I kept the example simple by only using the TemplateColumn to contain all the data. However, you can use any number of different column objects within the DataGrid . For instance, you can have a TemplateColumn and a BoundColumn within the same DataGrid or two different TemplateColumns or two different TemplateColumns .

You'll also notice that I set the style for the column differently than I did in previous examples. I use the CssClass attribute to set the HeaderStyle and ItemStyle in this DataGrid (lines 58 “59); this enables you to use an external style sheet to set the style for DataGrid items.

The ItemTemplate (lines 66 “101) in Listing 7.3 uses a table to organize the data. One thing to be aware of when using HTML elements within the TemplateColumn is that all the elements will be repeated for every row in the data source. So if you have server controls or HTML elements (ex: images) that are large in size (Bytes) then the page might render very slowly. Figure 7.3 contains an illustration of this page when rendered.

Figure 7.3. The DataGrid using a TemplateColumn .
graphics/07fig03.gif
only for RuBoard


Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

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