The Big ASP.NET DataGrid Article, Part 2

Welcome back to the second part of this ASP.NET DataGrid mini-series. This week, we're looking at using HTML, hyperlinks, and formatting in your DataGrid, plus figure out color-coding and the many different ways of allowing the user to select rows... all condensed into standalone, easy-to-follow tips!

How to Use HTML in a Web Grid

It'd often be useful to display HTML in a Web grid. Many content management systems, for example, store HTML-formatted text in key fields. Wouldn't it be useful to see bold text as actual bold text, rather than a bundle of <b> tags?

Well, it's simple. Just use it!

Because the Web grid output is fed straight to a browser, with none of your cell text being encoded, any tags in your fields will be rendered directly. This means that, if you've used a bold tag, it'll be rendered as bold text. If you've used a line break or image, it'll be rendered as a line break or image.

Figure: Demonstating simple HTML in a Web grid

Now that's the sort of quick and simple tip I like!

Using Hyperlinks in Your Web Grid

Hyperlinks form the backbone of the World Wide Web. They turn a five-minute mail-checking session into an all-night mega-surf. They're important, they connect the Web—and, as such, it makes sense that you may want to use them in your Web grid.

How? You need to set up a special HyperlinkColumn object to be displayed in your grid, specifying which field contains the text to display for the link, and which contains the actual link destination (that is, the hyperlink URL).

In this example, we're going to imagine that we've got a table of company details containing address and Web site information. We'll be designing our grid hyperlinks using the visual Property Builder.

So, you have a DataGrid on your Web form. Right-click and select Property Builder. Under the General property sheet, ensure that the DataSource and DataMember options are selected. This tells the DataGrid what data it is working with. Next, choose the Columns property sheet. Under the list of available columns, move the fields you want to display in your grid (under Data Fields) across to the list of selected columns.

Finally, set up our hyperlink column. Move down in the list of available columns, select 'HyperLink Column', and move it across to the list of selected columns. You will see a bunch of properties below. First, choose the Text field—this will be displayed as the text to the hyperlink. Next, select the URL field—this should hold the ultimate destination of the link, a Web address. Note that the URL field will need to contain an "http://" prefix.

Top Tip: Does your database simply contain the Web address in www.karlmoore.com format rather than http://www.karlmoore.com? No fear. Just select your field, then, in the "URL format string" box, enter the text: http://{0}. This will insert "http://" before your field text.

Next, choose a target from the dropdown box. If you don't specify this property, it'll use the page default. Other options include selecting "_blank" to open in a new window, or perhaps "_search" to open in the IE search bar. You may also want to set text for the "Header text" box, which will set the title for that particular column.

Click on OK when finished, and then bind as usual (follow "Nine Steps to a Quick, Editable Web Grid" through to Step 5 for quick, read-only binding). Sorted—a quick and easy data list, hyperlinks and all!

The Big ASP.NET DataGrid Article, Part 2

Dates, Currency, Percentages: Formatting your Web Grid Data

Ask the DataGrid to show your information and it'll display exactly what it found in your database. It doesn't give a thought to formatting and frankly couldn't care whether it's dealing with dates, money, or percentages. The good thing is, you can make it care.

How? First, set up your DataGrid as normal. Then, right-click and click to open the Property Builder. Choose the Columns property sheet and uncheck the 'Create columns automatically at run time' box; then individually move the fields you wish to view over to the selected columns list.

Next, for each column you wish to apply special formatting for, click and enter a new value in the 'Data formatting expression' box. Here are the most requested expression types, ready to be customized to your exact requirements:

Expression Description
{0:C} Formats the data as a default currency item (ie, $39.95)
{0:D3} Formats the data as a zero-padded four-character wide number (ie, 0023)
{0:N2}% Formats the data as a two decimal place number followed by a '%' symbol (ie, 59%)
{0:0.0} Formats the data as a number, rounding to one decimal place (ie, 36.5)
{0:D} Formats the data as a long date string (ie, "Thursday, December 25, 2003"; see the following figure)
{0:dd-MM-yy} Formats the data as a dd-MM-yy date (ie, "20/05/04")

When you've finished entering formatting expressions, just click OK to close the DataGrid Property Builder and run your application. Hey, presto!

Top Tip: Whilst you're using the Property Builder, you may wish to further customize your DataGrid. For example, try changing the Header Text on the Columns sheet. Or, you may wish to select your column on the Format sheet, and select a new column width or specify alignment of the cell contents.

Note that a number of formatting attributes are derived from the default machine culture. For example, the "en-us" culture will display a $ as the currency symbol, whereas the "en-uk" culture will display the £ symbol. To change the culture, specify the culture attribute in the Page directive or in the Web.config file (add culture="xx-xx" to the default <globalization> section). You should be particularly aware of this if you are using an off-shore Web host.

Top Tip Looking to format data in your Windows application DataGrid? It's not as easy as you'd imagine. Read the MSDN article at http://msdn.microsoft.com/library/en-us/dv_vstechart/html/vbtchformattingwindowsformsdatagridvisualbasicprimer.asp to learn more.

Figure: A sample grid, with the order date field using the {0:D} formatting expression

The Big ASP.NET DataGrid Article, Part 2

Looking Good: Color-Coding Your Web Grid

Grids on Web pages are great—but, among the mass of information you're displaying, it's sometimes difficult to spot important data such as overdue orders, special offer products, or large expense accounts.

One technique for dealing with this is to color-code your Web grid. For example, you might want to check whether a particular field value is greater than 100. If it is, you may want to change the background color or alter the style of the text.

You do this by responding to the ItemDataBound event of the DataGrid, which fires once for each "item" being put onto the grid during a binding operation. We then check that the "item" is a proper data row (and not a header row, for example), analyze the value of a particular field, and then change it as appropriate.

Here's an example that checks the second cell for a number value greater than 50 (the second cell being index number one, following the zero-based numbering system). If it is greater, the individual cell containing the number is bolded, the fore color set to white and the back color to a purple variant. If the number is 50 or less, the back color for the whole row is set to a light gray ("white smoke") and the border style changed to dotted. Simply add the following code behind the ItemDataBound event of the DataGrid:

If e.Item.ItemType = ListItemType.Item Or _
  e.Item.ItemType = ListItemType.AlternatingItem Then
  If CType(e.Item.Cells(1).Text, Integer) > 50 Then
    e.Item.Cells(1).BackColor = Color.Plum
    e.Item.Cells(1).ForeColor = Color.White
    e.Item.Cells(1).Font.Bold = True
    e.Item.BackColor = Color.WhiteSmoke
    e.Item.BorderStyle = BorderStyle.Dotted
  End If
End If

Figure: My final color-coded Web grid

Little-Known Technique for Confirming Web Deletes

This next code technique is a real gem—one of those tips you rarely find printed, but, when you figure out how it works, you won't be able to get enough of it. This tip shows you how to run a snippet of JavaScript to confirm an action, such as the deletion of a record, all on the client side. Best of all, it takes just one line of code.

Simply add the following code behind your delete button:

MyDeleteButton.Attributes("onclick") = _
"return confirm('Are you sure you wish to delete this record?');"

This adds a small piece of JavaScript to run when the client-side "onclick" event occurs for the rendered HTML button. The "Are you sure?" prompt then appears, and, if the user confirms, a True is returned and the click is processed. Otherwise, it simply cancels itself out.

However, this doesn't accommodate those developers using actual Delete buttons in DataGrid columns. In such a situation, you need to catch the individual Delete buttons as the data bind occurs and add this "onclick" attribute.

The following snippet of code assumes that you have a Web DataGrid with Delete buttons in the first column (index zero). Note that it currently explicitly checks for a Button control, not a PushButton. (Ensure that the "Button type" is set correctly in the Property Builder, or alter the code.) Simply add the following to respond to the ItemDataBound event of the DataGrid control, ready to fire when any data bind occurs:

If e.Item.ItemType = ListItemType.Item Or _
  e.Item.ItemType = ListItemType.AlternatingItem Then
  If e.Item.Cells(0).Controls.Count > 0 Then
    If TypeOf (e.Item.Cells(0).Controls(0)) Is Button Then
      Dim btnDelete As Button = CType(e.Item.Cells(0).Controls(0), _
      btnDelete.Attributes("onclick") = _
        "return confirm('Are you sure you wish to delete this _
    End If
  End If
End If

And that's it: simple, effective, and pretty hush-hush.

Figure: Confirm your Web deletes in a Web grid, easily!

The Big ASP.NET DataGrid Article, Part 2

Selecting Multiple Web Form Grid Items, Hotmail-Style

Selecting and, say, deleting items one by one can be a real pain. E-mail services such as Hotmail and Yahoo! Mail recognize that and allow you to select multiple messages through a little checkbox, then zap them all at once. Well, anything Hotmail can do, we can do... and quicker.

To create a selection checkbox, first set up your Web DataGrid as normal—displaying anything from order information to mail messages. Next, right-click the DataGrid and select Property Builder. Choose the Columns property sheet and add a "Template Column" to the list of selected columns, moving it to the top of the list (the first column). Set the "Header text" value if you wish. Click OK when finished.

Back on your Web page, right-click on your DataGrid again, this time choosing Edit Template, then selecting your new Template Column. This is your template for this particular field. Drag and drop a CheckBox control into the ItemTemplate portion, changing its ID property to chkSelect. When finished, right-click on the DataGrid again and select End Template Editing. You should be able to see the difference on your DataGrid.

Next, add a button to your Web form. This will be the button your user clicks after selecting records to delete (or perform some other action upon). Add code behind the button Click event, similar to the following:

Dim objItem As DataGridItem
For Each objItem In MyDataGrid.Items
  ' Ignore invalid items
  If objItem.ItemType <> ListItemType.Header And _
     objItem.ItemType <> ListItemType.Footer And _
  objItem.ItemType <> ListItemType.Pager Then
    ' Retrieve the value of the check box
    Dim blnDelete As Boolean
    blnDelete = CType(objItem.Cells(0).FindControl("chkSelect"), _
    If blnDelete = True Then
      ' Delete this row from the underlying DataSet, ie.
      ' LocalDS.Tables(0).Rows(MyDataGrid.SelectedIndex).Delete
      ' You can also retrieve the value of a field on the row, ie.
      ' MyVariable = objItem.Cells(5).Text
      ' ... then rebind.
    End If
  End If

Here, our code walks through each valid item in the DataGrid, searching for our control in the first cell (zero index) and analyzing whether it's checked. If it is, that's where your code can step in to take action—probably deleting the record in the underlying DataSet, then rebinding, as per example code in the "Nine Steps to a Quick, Editable Web Grid" tip.

And that's it. You now should be able to select multiple cells and perform an operation en masse, such as a delete, in seconds! You may even want to merge this tip with the next for even more power over your data.

Figure: Selecting multiple items in our Web grid, Hotmail-style

Click Anywhere and Select, with a Web Grid

Web applications are not like Windows applications. We know that. But, by using tricks such as the SmartNavigation property (covered here some months ago), you can give your sites more intelligence, allowing them to be much more responsive and to work better.

This next tip adds to that repertoire. By using the following code, you can click anywhere in a DataGrid and have the record you were over selected (or, rather, have your code behind the SelectedIndexChanged event run). This is especially useful for those with a speedy Internet connection, or using an intranet site, where postbacks are hardly noticed.

Anyway, here's the code. It assumes the very first column contains a Select button of the PushButton variety (you need to add this and any related code yourself, however; you can make the actual button invisible through the Property Builder, if you wish to do so). Our code finds this Select button and, through the highly hush-hush GetPostBackClientHyperlink function, returns the name of the script that runs when that button is clicked. This script is then set to run whenever the onclick event of your row runs. In other words, when the user clicks anywhere on your row, the Select button script kicks into play!

Ready to go? Just add the following code to respond to the ItemDataBound event of the DataGrid control:

If e.Item.ItemType = ListItemType.Header Or _
  e.Item.ItemType = ListItemType.Footer Or _
  e.Item.ItemType = ListItemType.Pager Then Exit Sub
If e.Item.Cells(0).Controls.Count > 0 Then
  If TypeOf (e.Item.Cells(0).Controls(0)) Is Button Then
    Dim btnSelect As Button = CType(e.Item.Cells(0).Controls(0), _
    e.Item.Attributes("onclick") = _
      Page.GetPostBackClientHyperlink(btnSelect, "")
  End If
End If

Figure: Click anywhere and select, with this crafty code

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book, plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

This article was originally published on February 26th, 2004

About the Author

Karl Moore

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date