DataGrid Column Properties

Chapter 5 - Reading Data using the Dataset Object
byJohn Kauffman, Fabio Claudio Ferracchiatiet al.?
Wrox Press ?2002

To this point, we've accepted our DataGrid columns as they were presented to us by the data source. However, the DataGrid is quite capable of applying customization to each column on an individual basis, controlling such things as the column heading, the appearance of the data in a column, and even whether a column should appear at all. The techniques involved are not difficult, as long as you remember the following:

  • Turn off the automatic generation of columns

  • Create columns of your own, and set their properties within the DataGrid object

  • Be careful to follow HTML element rules, and to use the correct field names

  • The formatting syntax is tricky, so type carefully

Starting at the top of that list, we must set the DataGrid's AutoGenerateColumns attribute to False. Then, we can add an element named <Columns>, and within that as many BoundColumn controls as we need. Each bound column can have several of its own attributes, as we will discuss below, but the most basic one is DataField, which specifies the actual column in the DataTable to bind to the DataGrid.

       <asp:DataGrid  runat="server"                     AutoGenerateColumns="False">         <Columns>           <asp:BoundColumn DataField='myField1" />           <asp:BoundColumn DataField="myField2" />         </Columns>       </asp:DataGrid> 

Many field names in data stores use abbreviations, making them difficult to understand for web site visitors. To overcome this kind of problem, the BoundColumn control supports the HeaderText attribute, which can provide a more friendly column header. We can use this in the following way:

           <asp:BoundColumn DataField="my Field1" HeaderText="myCustomText" /> 

It's even possible to include HTML elements in the value you assign to the HeaderText attribute, as this string is sent directly to the browser.

Another likelihood is that we'll want to format the values within a column, for an easier-to-read display. For this, we use an attribute of the BoundColumn control called DataFormatString, which is always followed by a value in double quotes. The value has four parts, built around a set of braces and a colon; for a BoundColumn that contains price information, it might look something like this:

           <asp:BoundColumn DataField="myField1"                            DataFormatString="Our Price {0:C2} postpaid" /> 

To the left of the opening brace, we have literal characters (such as "Our Price" here). Then, inside the braces, but to the left of the colon, we have a number that's always zero for a DataGrid (because there's only one value in each cell of the grid). To the right of the colon, but still inside the braces, is a code that will affect the formatting of values in this column. Finally, to the right of the braces, we have some more literal characters ("postpaid" above).

The codes for formatting values consist of a letter followed by a number. The letter determines the general formatting, and the number determines the degree of accuracy. However, the same letter codes can mean different things, depending on the type of data you're dealing with. For example, D for numbers means decimal, while for dates it means 'long' (that is, verbose) output. Furthermore, upper and lower case letters can denote different patterns (d is a 'short' date, while D is a 'long' date). On top of these complexities, keep in mind that formats for dates and currency will vary according to localization (4/10/2002 means different days in Lancaster, Pennsylvania and Lancaster, England - in the US, dates are formatted month/day/year; in the UK, they're formatted day/month/year).

In the following table (which isn't exhaustive - check the documentation for the others), the raw data used for numbers and currency is 12.6789, while for dates it's midnight at the start of March 23, 2003.

Format

Syntax

Result

Notes

Numbers

{0:N2}

12.68

Number indicates the number of decimal places to display.

Numbers

{0:N0}

13

Numbers are rounded to the nearest integer.

Currency

{0:c2}

$12.68

No difference between C and c.

Symbol will be local (server) currency symbol.

Currency

{0:c4}

$12.6789

Number determines the number of decimal places to display.

Currency

"¥{0:N2}"

¥12.68

Add currency symbols other than the server's default with literal characters, and using numeric format.

Scientific Notation

{0:E3}

1.27E+001

Number represents total number of significant figures.

Percent

{0:P}

1,267.89%

No difference between P and p.

A value of 1 will appear as 100%.

A value of 0.01 will appear as 1%.

Dates

{0:D}

Sunday, March 23, 2003

Upper case gives long date (day plus date in words).

Dates

{0:d}

3/23/2003

Lower case gives short date (date in numbers).

Dates

{0:f}

Sunday, March 23, 2003 12:00 AM

Long date plus hours and minutes.

Dates

{0:F}

Sunday, March 23, 2003 12:00:00 AM

Long date plus hours, minutes, and seconds.

Date

{0:s}

2003-03-23T00:00:00

ISO 8601 sortable.

Times

{0:T}

12:00:00 AM

Time (t gives no seconds).

The last thing that we suggested might be useful to do is to show or hide DataGrid columns. This can be done by setting the Visible attribute of the column to "False":

           <asp:BoundColumn DataField="myField1" Visible="False" /> 

As you'd expect, the default value of Visible for a column is "True". To change the value in response to a user action, we'd use the following syntax:

    myDataGrid.Columns(myColumnIndexAsInteger).Visible = False 

Let's put all of the above to the test, with the help of another of our worked examples.

Try It Out - DataGrid Column Properties

start example

We will put together a page that shows the first few orders from Northwind, with modifications. For instance, we'll display the order ID number, but the CEO is planning to move to a new numbering system, and has asked us to pad them with leading zeros until they have seven digits (she also likes to see a # in front of the order number). The shipped-to address should also appear, but it'll be possible to hide it by clicking on a check box. In addition, we'll show the shipped date (but only the date, not the time), and some more descriptive column headings.

  1. Create a file called DataGrid_properties.aspx and add the following code:

     <%@ Import namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <html>   <head><title>DataGrid Bound Columns</title></head>   <body>     <h3>DataGrid Bound Columns</h3>     <form runat="server">       <asp:CheckBox  runat="server"                     AutoPostBack="True"                     Text="Show Address for Shipping"                     OnCheckedChanged="CheckChanged" />       <asp:DataGrid  runat="server"                     AutoGenerateColumns="False">         <Columns>           <asp:BoundColumn DataField="OrderID"                            HeaderText="Order<br/>Number"                            DataFormatString="#{0:D7}" />           <asp:BoundColumn DataField="ShipAddress"                            HeaderText="Shipped<br/>To"                            Visible="False" />           <asp:BoundColumn DataField="OrderDate"                            HeaderText="Shipped<br/>Date"                            DataFormatString="{0:d}" />         </Columns>       </asp:DataGrid>     </form>   </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 * FROM Orders WHERE OrderID < 10255 " &                          "ORDER BY OrderID"   Dim objAdapter As New SqlDataAdapter(strSQL, objConnection)   Dim objDataSet As New DataSet()   objAdapter.Fill(objDataSet)   objConnection.Close()   dgOrders.DataSource = objDataSet   dgOrders.DataBind() End Sub Sub CheckChanged(S As Object, E As EventArgs)   dgOrders.Columns(1).Visible = chkShowAddressee.Checked End Sub </script> 

  2. Viewing the above page will give the screen below. Notice the improved text in the header of each column.

    click to expand

  3. When we click on the check box, we get the additional column, as follows:

    click to expand

end example

How It Works

The form we create within the HTML section implements several of the features we discussed above. The first thing to note is that we set the check box's AutoPostBack attribute to True, and wired it to the CheckChanged() event handler, which will control the showing and hiding of the shipping address column. It's also worth pointing out that this is a single check box, rather than the list we used in the last chapter, although the syntax for using it is very similar.

            <asp:CheckBox  runat="server"                          AutoPostBack="True"                          Text="Show Address for Shipping"                          OnCheckedChanged="CheckChanged" /> 

Now we set up our DataGrid control, but this time we format each column individually. Take a good look at how we create each <asp:BoundColumn> element within the <Columns> element; a common mistake here is to go right to the first column and forget the opening <Columns> tag.

For our first column, we use the HeaderText attribute to output the text Order<br/>Number in place of the real field name. The values displayed in the column will be enhanced with a specific format: we want the data preceded with a # character, and then we want each number to be padded with leading zeros to seven digits. Recall that the zero to the left of the colon is always the same for BoundColumn formatting.

           <asp:DataGrid  runat="server"                         AutoGenerateColumns="False">             <Columns>               <asp:BoundColumn DataField="OrderID"                                HeaderText="Order<br/>Number"                                DataFormatString="#(0:D7)" /> 

Our second column again uses our own text instead of the field name. Also, since we start with our check box empty, we want to initialize this column to be invisible.

           <asp:BoundColumn DataField="ShipAddress"                            HeaderText="Shipped<br/>To"                            Visible="False" /> 

The third and final column takes another format - in this case, we want a short date.

           <asp:BoundColumn DataField="OrderDate"                            HeaderText="Shipped<br/>Date"                            DataFormatString="(0:d)" />         </Columns>       </asp:DataGrid> 

Moving on to the VB.NET code, we set up the connection as we've done several times before, and then provide the SQL query string. In it, you can see how we limit ourselves to the first few orders by using a WHERE clause. (The first order number in the table is 10248.)

       Dim StrSQL As String = "SELECT * FROM Orders WHERE OrderID < 10255 " & _                              "ORDER BY OrderID" 

We use the SQL query as the first argument to instantiate our data adapter, which then fills a DataSet object. We finish by binding this DataSet to the DataGrid.

      Dim objAdapter As New SqlDataAdapter(strSQL, objConnection)      Dim objDataSet As New DataSet()      objAdapter.Fill(objDataSet)      objConnection.Close()      dgOrders.DataSource = objDataSet      dgOrders.DataBind() 

You'll remember that when we created the check box, we specified that when the status changed, the CheckChanged() method should be called. The logic of this method is not hard to divine: when the box is checked, we want the column to be visible; when it's unchecked, the column should disappear. Both of these properties are implemented using Boolean values, so we can just set one to the other! Since bound columns are indexed (from zero) in the order they were created, the shipped-to column is Columns (1).

    Sub CheckChanged(S As Object, E As EventArgs)      dgOrders.Columns(1).Visible = chkShowAddressee.Checked    End Sub 

To summarize what we've learned about bound columns, remember that you can use them to create better headings for your columns, and to configure the format of the data they contain. Bound columns can also have their Visible property changed at runtime.



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