Data Grids

Chapter 4 - Data Readers, Command Objects, and Web Server Controls
byJohn Kauffman, Fabio Claudio Ferracchiatiet al.?
Wrox Press ?2002

In classic ASP, it was possible to spend a tremendous amount of time writing code to display, sort, hyperlink from, and otherwise work with tables of data. This author spent more time troubleshooting and maintaining such code than he did writing database queries and business logic! In ASP.NET, however, Microsoft has created the DataGrid control, which is very complex internally, but satisfyingly easy to use. Simply by setting the control's properties and child elements, you can instruct it to:

  • Write HTML tags to create a <table>, automatically sensing the number of columns and rows needed to fit the data

  • Write HTML tags to apply table-level formatting

  • Write HTML tags to implement row styles that the programmer creates

  • Write HTML tags to format columns, including formats such as 'buttons' and 'hyperlinks'

  • Divide data into pages, and provide navigation tools to move through the pages

  • Write HTML tags to implement sorting on a column selected by the visitor

  • Write HTML tags to allow the user to edit data in a selected row

If you like, you can look at the DataGrid as a way either of saving you hundreds of dollars in buying third-party controls, or of saving yourself weeks of time trying to get all those features to work. In this chapter, we will cover the first three topics in the above list. In the Chapter 7, we'll discuss editing data.

Formatting the Entire Grid

Having used them a number of times, you've already seen the basics of editing and filling a DataGrid. One of the things that we've done regularly, and is well worth remembering, is to place the grid inside a <form> element; this isn't always necessary, but you'll need to do it in order to have any kind of sorting or editing facilities, and it's a good habit to get into.

Moving on to its appearance, the DataGrid supports the traditional BackColor and ForeColor properties - either Internet Explorer's 16 basic colors (aqua, black, blue...), or Netscape's 135 colors (AliceBlue, AntiqueWhite, AquaMarine, etc.). You can also use the RGB system. The syntax is simple:

      <asp:DataGrid  runat="server"                    ForeColor="purple"                    BackColor="silver" /> 

Or:

                    ...                    ForeColor="#FFOOFF"                    ... 

Instead of setting a BackColor, we can use the BackImageURL attribute to specify an image - but although this sounds easy, it tends to become more problematic in real life. The image does not automatically expand to fit the grid - rather, it repeats - so you have to be careful about the image you choose.

                    backImageURL = "MyImage.gif" 

We can set the location of the grid on the page with the HorizontalAlign attribute. The default value for this is "NotSet", which generally means 'left'; you can change it to "left", "center", or "right" There is no property for vertical alignment of the entire grid.

As with a regular HTML table (and, therefore, as you'd hope), you can set the grid border's color, width, and style, with the latter including options like "solid", "dashed", and "dotted". Note that the BorderColor affects both internal and external borders, while the width and style are only applied to the external borders of the grid. The code below illustrates this difference; color options are the same as for the background and foreground.

                    BorderStyle="dashed"                    BorderWidth="5"                    BorderColor="gray" 

The above code yields the following on the browser screen, demonstrating that the border style and width only affect the outer border.

click to expand

We can set standards for the content of cells with the Font-Name, Font-Size, CellSpacing, and CellPadding properties. The second pair in that list behaves in the same way as the identically named attributes of the radio button list that we saw earlier. Font-Name and Font-Size work the same as for plain HTML tags, as in the following example:

                    CellSpacing="2"                    CellPadding="10"                    Font-Name="verdana"                    Font-Size="20" 

The DataGrid control also includes Enabled and Visible properties. Visible="False" means that the table is hidden from the viewer (useful when you have the control on the page, but no data to display), while Enabled determines whether the visitor can interact with clickable items on the data grid (such as a button to begin an update process). Grids that are Enabled="False" will be gray.

Row Formatting

ASP.NET offers an easy, three-step technique for formatting the rows that appear in several of its web server controls. First, you need to understand how ASP.NET names the different types of rows that can appear in a grid. Second, you need to set some properties of the data grid itself. Third, you create a style for each type of row, using one of several syntactic possibilities. After that, ASP.NET does the rest.

In all, there are seven row types. The Header row contains the names of the columns, while the Footer will be added to the bottom of the grid, after the last row of data. The data itself is presented in Item rows, of which there are four sub-types. Item itself is the default, but there's also an AlternatingItem (which will give a horizontally striped look to the grid), a SelectedItem (if selection of rows is allowed), and an EditItem (for rows that are being edited - see Chapter 7).

That's six so far; the seventh type is the Pager, which we'll look at later on when we examine how to add some hyperlinks to navigate through the pages when there's too much data to fit in one grid. It's worth noting here that for paging to be possible, you need to set AllowPaging="True". Similarly, in order for the header and footer rows to be displayed, the ShowHeader and ShowFooter attributes must be set to "True". The former has this value by default, but the latter does not.

As you can see below, each type of row can get its own formatting. The column on the left indicates the row type name, while on the right are two columns of examples.

Header

FirstName

LastName

Item

Nancy

Davolio

AlternatingItem

Andrew

Fuller

Item

Janet

Leverling

AlternatingItem

Margaret

Peacock

Item

Steven

Buchanan

SelectedItem

Robert

King

EditItem

Laura

Callahan

Footer

Check daily for specials

 

Pager

<Previous Next>

 

It's in this area that ASP.NET is at its most confusing. It has two terms that can be tricky to differentiate, because each applies to the same seven kinds of rows.

  • Styles determine the formatting of the rows, such as font size and background color. For example, you'd use a Style to apply a blue background to the Header row.

  • Templates determine what information (HTML tags, data and text) will appear in the row. For example, you'd use a Template to show the words Check daily for specials in a Footer row.

In the DataGrid control, templates affect columns, rather than rows.

There are three forms of syntax that can set styles for a row. The first syntax is the most compact, and uses an attribute of the <asp:DataGrid> element:

          <asp:DataGrid  runat = "server"                        HeaderStyle-backcolor="lightgray" /> 

In the second option, which is probably the most easily readable, we specify a style element within the <asp:DataGrid> element:

          <asp:DataGrid  runat="server">            <HeaderStyle backcolor="lightgray" />          </asp:DataGrid> 

The third technique is to refer to a class that you've created in a Cascading Style Sheet (CSS). The following example assumes that you have a style named MyHeaderStyle in a CSS named MyStyleSheet.

    <head>      <style ref="MyStyleSheet" type="text/css">        .MyHeaderStyle (property1: value1; property2: value2;}      </style>    </head>    <body>      <asp:DataGrid  runat="server"                    HeaderStyle-Cssemphasis">MyHeaderStyle" />       ... 

In ASP.NET, there are more than a dozen properties that can be set in row styles, including:

  • BackColor and ForeColor.

  • Height, Width, and Wordwrap of a row. (Note: the width of the table will be determined by the widest of all the styles. In other words, don't bother setting one style to create a narrow table if another style will create a wide table. The table will end up wide.)

  • HorizontalAlign and VerticalAlign.

  • Font properties, such as name and size.

  • Border width, color, and style.

  • CSS class.

As in so many situations, it's easy to go overboard on these style properties, and to end up with a visually confusing grid. But if you set each property to implement color-coding, or to make the text easier to read, then you will improve the usability of your page.

Try It Out - DataGrid Row Styles

start example

Let's imagine that your boss has asked you to write the ASP.NET code to display the following page. The code, which we'll analyze in full, applies styles to the header, footer, and "alternating item" rows in order to achieve its results.

click to expand

  1. Open your editor, create a page named Row_styles.aspx and enter or download the following code:

     <%@ Import namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <html>   <head><title>Data Grid Row Styles</title></head>   <body>     <h3>Data Grid Row Styles</h3>     <asp:DataGrid  runat="server"                    ShowHeader="True"                    ShowFooter="True"                    CellPadding="5">       <HeaderStyle BackColor="black"                    ForeColor="white"                    HorizontalAlign="center"                    Height="50" />       <AlternatingItemStyle BackColor="lightgray" />       <FooterStyle BackColor="black"                    ForeColor="white" />     </asp:DataGrid>   </body> </html> <script language="VB" runat="server"> Sub Page_Load(Source As Object, E As EventArgs)   Dim strConnection As String = ConfigurationSettings.AppSettings("NWind")   Dim objConnection As New SqlConnection(strConnection)   Dim strSQL As String = "SELECT CategoryID AS [Our Number], " & _                          "CategoryName AS [Category Name], " & _                          "Description AS [Category Includes] " & _                          "FROM Categories"   Dim objCommand As New SqlCommand(strSQL, objConnection)   objConnection.Open()   dgCategories.DataSource = objCommand.ExecuteReader()   dgCategories.DataBind()   objConnection.Close() End Sub </script> 

end example

How It Works

There are three areas of interest in this page: the SQL statement, the general formatting of the DataGrid control, and the specific row styles. We'll start with the SQL statement, which includes a feature that we haven't used before. Aliasing allows us to take the names of the fields in the database and change them so that they look better when displayed, without losing the link between the two.

It's worth mentioning why there's a need for aliases. Developers follow a syntax error minimization convention of not having spaces in table and column names (for instance, CategoryName). For display purposes, however, the presence of spaces makes things much more readable (Category Name). Aliases exist to bridge this gap.

The creation of aliases requires the SQL AS keyword. You write the original field name, followed by AS, followed by your chosen name. After the query has been executed, you (and ADO.NET) will refer to the fields by using the alias. If the alias has a space in it, you must use brackets, as we did here.

      Dim strSQL As String = "SELECT CategoryID AS [Our Number], " & _                             "CategoryName AS [Category Name], " & _                             "Description AS [Category Includes] " & _                             "FROM Categories" 

Moving on to the formatting of the DataGrid control, we know that we want a header and footer, so we explicitly set the appropriate properties to "True".

         <asp:DataGrid  runat="server"                       ShowHeader="True"                       ShowFooter="True" 

While we're at it, we also add some padding to all of the cells in the grid, making the resulting table a little easier on the eye.

                       CellPadding="5"> 

Now we get to the individual row styles. The top row will be of the HeaderStyle.

         <HeaderStyle BackColor="black"                      ForeColor="white"                      HorizontalAlign="center"                      Height="50" /> 

We get the gray and white background stripes by setting the AlternatingItemStyle element's BackColor attribute to lightgray.

         <AlternatingItemStyle BackColor="lightgray" /> 

And finally we format the footer to look the same as the header, even though it contains no text in this particular example.

            <FooterStyle BackColor="black"                         ForeColor="white" />          </asp:DataGrid>        </body>      </html> 

In addition to the three we've used here, the rows in DataGrids can be formatted using four other style elements: ItemStyle, EditItemStyle, SelectedItemStyle, and PagerStyle. Other controls will make different style properties available, and you should consult the documentation to discover what works with the control you're using.

Going Further with Displaying Data

In the next chapter, we'll take a look at some more ways to format the data in tables, several of which are only available when the data source for the DataGrid is a dataset object. We'll also take a look at the Calendar control, and the techniques for working with controls that bind a single value of data, such as a text box.



Beginning ASP. NET 2.0 and Databases
Beginning ASP.NET 2.0 and Databases (Wrox Beginning Guides)
ISBN: 0471781347
EAN: 2147483647
Year: 2004
Pages: 263

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