When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, May 22, 2002

An Extensive Examination of the DataGrid Web Control: Part 4
By Scott Mitchell


The Fourth Part in a Multi-Part Series
This article is the fourth piece of a multi-part series on using the DataGrid Web control that will span several weeks. The ASP.NET DataGrid Web control, which displays database information in an HTML table, is highly versatile. The basics of the DataGrid were discussed in Part 1; information on specifying display properties of the DataGrid was discussed in Part 2. In Part 3 we examined how to associate custom events with the DataGrid. In this part we'll look at how to extend Part 3 to provide custom sorting on the results of a DataGrid!
  • Read Part 5
  • Read Part 6
  • Read Part 7
  • Read Part 8
  • Read Part 9
  • Read Part 10
  • Read Part 11
  • Read Part 12
  • Read Part 13
  • Read Part 14
  • Read Part 15
  • Read Part 16
  • Read Part 17
  • Read Part 18
  • - continued -

    ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start is author Scott Mitchell's most recent book, which thoroughly examines three of the most commonly used ASP.NET Web controls: the DataGrid, DataList, and Repeater. These three Web controls can be difficult to master due to their numerous features and capabilities. With this book, you'll quickly become an expert, learning the gritty details and true capabilities of each. This 400+ page book explores the topics in this article series in much greater depth, along with examining various topics and techniques not covered here.

    Scott Mitchell is the editor and founder of 4GuysFromRolla.com, author of the An Extensive Examination of the DataGrid Web Control article series, and author of numerous other ASP and ASP.NET books.

    [Buy this Book]
    [Visit the Book's Companion Web Site]

    Introduction
    Recall that in Part 3 of this series we examined how to associate certain events, like the click of a button, with actions. For example, in a live demo we showed how to allow the user to click a "Details" button to show specific information about one of the rows in the DataGrid. In this part we'll expand on the notion of tying buttons in the DataGrid to an action to allow the end user to sort the contents of the DataGrid on the fly.

    Preparing a DataGrid for Sorting
    You'll be pleased to learn that adding support for sorting to a DataGrid is very simple, and can be broken down into the following three steps:

    1. Set the AllowSorting property of the DataGrid to True. If the DataGrid's AutoGenerateColumns property is set to False, specify the SortExpression property in the BoundColumn controls that represent the rows you'd like the user to be able to sort on.
    2. Create a sort event handler that repopulates the DataGrid with the sorted data, and specify the name of this sort event handler in the DataGrid's OnSortCommand event.
    3. Create a function that will allow you to grab the data from your data store in sorted format.

    Let's tackle these steps one at a time. For the first step, you need to specify the AllowSorting property in your DataGrid, like so:

    <asp:DataGrid runat="server" id="id" 
                AllowSorting="True"
                ... >
      ...
    </asp:DataGrid>            
    

    If you have the AutoGenerateColumns property set to True (the default) you've completed step 1. (Recall that if the AutoGenerateColumns property set to True then the columns of the DataGrid are determined by the columns in the source you are binding to the DataGrid. If the AutoGenerateColumns property set to False, then you have to explicitly specify what columns should appear in the DataGrid via BoundColumns. See Part 2 of this series for more information on this topic.) If, however, you have the AutoGenerateColumns property set to False, then you will need to decide what column(s) you want to allow the user to sort on. For all the columns you want to let the user sort, you must add a SortExpression property to the BoundColumn. Note that you should give this SortExpression property the name of the column in the database:

    <asp:DataGrid runat="server" id="id" 
                  AutoGenerateColumns="False"
                  AllowSorting="True">  
      <Columns>
        <asp:BoundColumn DataField="dbField"  />
        <asp:BoundColumn DataField="dbField2" 
                      SortExpression="dbField2"  />
      </Columns>
    </asp:datagrid>
    

    In the above example the DataGrid will have two columns, one binding to the database column dbField and the other to dbField2. The latter column will be able to be sorted while the first will not (since the latter has a SortExpression property specified while the former does not).

    Creating a Sort Event Handler
    By adding the AllowSorting property to True, the DataGrid, when rendered, will have in its header for each column a hyperlink. When clicked, a postback occurs and the sort event is raised. When this event is raised we'd like to have a sort event handler fire that requeries the data store, getting the data in the specified sorted order, and rebinds it to the DataGrid. In order to have this happen we need to do two things: create a sort event handler and specify the event handler for the DataGrid's sort event.

    First, when creating the event handler you must use the following definition:

    Sub SortEventHandler(sender as Object, e as DataGridSortCommandEventArgs)
       ...
    End Sub
    

    (Of course you can name the variables sender and e whatever you like - the important part is realizing that you need to have your event handler accept two variables: an Object and a DataGridSortCommandEventArgs.)

    Inside your event handler you can retrieve the name of the column that was sorted via: e.SortExpression. If you explicitly specified the SortExpression property in a BoundColumn, then the value of e.SortExpression is the value of the SortExpression property; if you did not specify a SortExpression property (because you had AutoGenerateColumns set to True), then the value of e.SortExpression is the value of the database column name that represents the column clicked.

    Once you sort event handler is created you need to associate it with the DataGrid's sort event, so that when this event is raised the proper event handler is fired. To accomplish this simply set the DataGrid's OnSortCommand event handler to the name of the sort event handler you created, like:

    <asp:DataGrid runat="server" id="id" 
                    AllowSorting="True"
                    OnSortCommand="NameOfSortEventHandler">
      ...
    </asp:DataGrid>
    

    At this point a couple of demos might be helpful. I've created two of them, one that uses AutoGenerateColumns set to True, and one that uses AutoGenerateColumns set to False. Both examples set the AllowSorting property to True and have a very simple sort event handler that does nothing but set a label Web control's Text property to the value of e.SortExpression. Note that the DataGrid is enclosed in a server-side form (<form runat="server"> ... </form>) - this is essential, since we are dealing with postbacks here.

    All that we have left to do is to create a function that retrieves the data in a specified sorted order. Once we have this function the code for our sort event handler becomes trivial - we simply need to call this function, passing in the SortExpression, and then setting its result to the DataGrid's DataSource and rebinding the DataGrid (via DataBind()). We'll look at how to accomplish this in Part 2 of this article.

  • Read Part 2!


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES