January 27, 2021
Hot Topics:

The Big ASP.NET DataGrid Article, Part 3

  • By Karl Moore
  • Send Email »
  • More Articles »

Speedy, Personalized Web Data Binding

If you're simply viewing data using your Web grid and want to personalize the output a little more, then you'll be pleased to know that, despite the rumors, it's actually pretty simple and can be done without even delving into those special <asp> tags you find dotted in most books.

To personalize the DataGrid, first set it up as usual. In the General property sheet of the Property Builder, choose a DataSource, DataMember, and an optional Data key field. Under the Columns property sheet, uncheck "Create columns automatically at run time" and instead add the data fields you require to the list of selected columns.

Now, cycle through each of the columns in the selection column list and click on the "Convert this column into a Template Column" link at the bottom of the property sheet. This takes the standard DataGrid method of displaying information from a DataSource and changes it into a template, letting you edit how each column field looks. Click on OK to close the Property Builder.

Next, right-click on the DataGrid, select Edit Template, and look at the ItemTemplate section for one of your columns. You'll notice that it already contains one label, which links to a field in your table through the DataBindings property.

Begin your customization. You may, for example, add two Label controls and change the DataBindings property so that one points to, for example, Container > DataItem > FirstName, while the second binds to Container > DataItem > LastName. You could perhaps add a little text as a prefix to the field value, too.

There are more possibilities. You may add a HyperLink control and change DataBindings so that the Text and NavigateUrl are provided by fields from your table. You might use your data to supply the ImageUrl property of an ImageButton control—simply select the field containing your filename. (You may also wish to change the 'Format' box to something such as http://www.yoursite.com/images/{0} if you wish to add a prefix to your filename—the {0} will get replaced with the data from your field.) You could even merge all of the above and create a single column listing of all your catalogue products: pictures, descriptions, purchase links and all.

Top Tip: Want to customize even further? Delve straight into the HTML. Right-click on your DataGrid and select View HTML Source.

When finished, right-click on the grid and select End Template Editing. Then, bind view your data as normal.

In brief, with the ItemTemplate (and related) sections, you can really push the way your DataGrid displays its simple bound data. Truthfully, in-grid editing is troublesome, but when you're just viewing... the power is yours!

Top Tip: In case you're wondering, the DataList control works in much the same way as the DataGrid when you get to this level of customization. It holds advantages and disadvantages over the DataGrid—for example, although you can't edit through the DataList, you can list rows horizontally or vertically. The brother Repeater control can also be bound, but it requires editing of the <asp> tags in HTML and is more limited in the way it works. Look up "DataList control, vs. other list controls" in the help index for more information.

Quick and Easy Data Paging, with Your Web Grid

Most Web developers tend to shiver at the mere mention of the word paging. Even old-hat ASP.NET programmers are a little confused over its implementation. Many of the new .NET books devote a chapter or so to the subject—but it really isn't that complicated.

Paging is a method of splitting results in your DataGrid over multiple "pages." Google uses paging in its search results. Yahoo! uses paging if it can't fit all its matching sites onto one page. It's useful—and can be set up in seconds.

First off, set up your DataGrid as usual. Add all your regular binding code. When you're done, right-click on the grid and select Property Builder. Choose the Paging property sheet and check "Allow paging". Alter the page size so it represents the number of items you want to display on any one page. You may also want to change the navigation text just below. Click OK when finished.

Next, add code similar to the following to respond to the PageIndexChanged event of your DataGrid control:

MyDataGrid.CurrentPageIndex = e.NewPageIndex
' Bind your data again here. You could load DataSet
' from ViewState, database, etc. For example:

And that's it—just fire off your DataGrid as normal and you've got instant paging!

Top Tip: If you're going to use editing with paging, watch out when updating your DataSet. If you're doing it purely on position, remember that, after you move to a new page, your first item will not correlate with the first item in your DataSet. You'll have to code around this. You can find out the current page by looking up the .CurrentPageIndex property, and find out the number of items displayed per page with the .PageSize property.

Figure: Simple paging in seconds!

Sorting in Seconds, with Your Web Grid

When you're looking at a grid full of data, it's natural to want to order it somehow. You may want to view employees by salary amount, from the highest paid to the lowest. Or view a customized query showing an alphabetical list of sales staff and their respective telephone numbers.

That's all easy, with sorting—something the ASP.NET DataGrid provides excellent built-in support for. Here, I'm going to demonstrate the sorting technique in its simplest form; however, you can greatly expand upon this to build a much more elegant solution.

First of all, set up your DataGrid as normal, adding all your regular binding code. When done, open up the Property Builder and in the General property sheet, set the DataSource, DataMember, and optional Data key field for your table. Moving on to the Columns property sheet, uncheck "Create columns automatically at run time", and then move all the fields you want to view in this DataGrid across to the list of selected columns.

Next—and this is the important bit—specify a "sort expression" value for each of the columns you're going to allow your users to sort by. This will turn the column header into a hyperlink that, when clicked, will fire an event. This event will receive your sort expression value as an argument, which you then can use to reorder the data appropriately. So, select a few columns and a related sort expression. For the purpose of this example, stick with the default of the field name as the sort expression. (You'll see why it makes things easier next.) Click on OK when finished.

Now, we're ready to add code to handle this sorting ourselves. No, this process isn't automatic—we need to somehow reorder our data and then rebind to the DataGrid. I'm going to handle this by simply requerying my data source, although with an extra ORDER BY clause. Here's the code I'll be entering to respond to the SortCommand event of my DataGrid:

' Reset index, in case on a different page
MyDataGrid.CurrentPageIndex = 0
' Change SELECT statement, using the passed in 'sort expression'
' value we specified earlier
MyDataAdapter.SelectCommand.CommandText = _
  "SELECT * FROM mytablename ORDER BY " & e.SortExpression
' Refresh data and rebind
MyDataGrid.DataBind ()

Here, you can see that my code initially resets the index, in case we're on another "page" of the DataGrid somewhere. It then uses our DataAdapter to alter the underlying SELECT statement, ordering by the current sort expression (the field name we specified earlier). Note that there are other, more elegant ways of handling this, rather than directly rewriting the SELECT text, but, for simplicity and demonstration purposes, this technique's a winner. Finally, we refill the DataSet and bind it back to the DataGrid.

We're almost there now. To activate all your hard work, all you need to do is select your DataGrid and change its AllowSorting property to True.

And that's it! Your grid will now allow you to click on the header text of any of your "sort-aware" columns and put them in correct, ascending order. With a little imagination, you can also expand on this code base to allow "reverse sorts," too. Have a play around!

Figure: Click and sort, in just a few lines of 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.

Page 3 of 3

This article was originally published on March 3, 2004

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

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