asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














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

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Introducing the ASP.NET 2.0 GridView Control - Part 2
By Ziran Sun
Rating: 3.5 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

  • download source code
  • In the first part of this article, I gave a brief introduction to one of the new data-bound controls introduced in the .NET Framework version 2.0 -- the GridView. In this part, I'll continue examining this versatile control and introduce you to some of its more powerful capabilities.

    Last time we focused mainly on just getting data from the database onto the page. This time we'll cover going the other way and actually editing some of that data as well and filtering the display so that you only see the data you want to see.

    Editing Data in the GridView Control

    In the first part of this article, we covered using the GridView to display data on a web page. The next step in most applications involves actually making changes to that data. For this code sample, I'm going to pick up where we left off in part one. If you remember we had built a web page with a data source control configured to pull data from the SQL Server pubs sample database on the local machine. This datasource was used to pull in the data which was then displayed by the GridView control. That part will stay the same, we're simply going to add on to it.

    The first change we need to make is to our SqlDataSource control. Until now we had only provided the control with a command to select data. Now we're going to add commands to delete and update data. Unlike our simple select command, these commands will require parameters. In order to delete a row, we need to know which row to delete. Likewise, if we want to update a row's data, we need to know what data to put where. This is where parameters come into play. If you look at the code listing below you'll see that I've added the DeleteParameters and UpdateParameters sub-tags to the SqlDataSource control and have indicated the parameters and their data types that our delete and update commands require.

    <%@ Page Language="VB" %>
    <html>
    <head>
      <title>Introducing the ASP.NET 2.0 GridView - Editing</title>
    </head>
    <body>

    <form runat="server">

      <asp:SqlDataSource ID="mySqlDataSource" runat="server"
        ConnectionString = "Server=(local);Database=pubs;User Id=sa;Password=password;"
        SelectCommand = "SELECT * FROM authors;"
        DeleteCommand = "DELETE FROM authors WHERE au_id=@au_id;"
        UpdateCommand = "UPDATE authors SET au_fname=@au_fname, au_lname=@au_lname,
          address=@address, city=@city, state=@state, zip=@zip, phone=@phone,
          contract=@contract WHERE au_id=@au_id;"

      >
        <DeleteParameters>
          <asp:Parameter Name="au_id" Type="String" />
        </DeleteParameters>
        <UpdateParameters>
          <asp:Parameter Name="au_id"    Type="String" />
          <asp:Parameter Name="au_fname" Type="String" />
          <asp:Parameter Name="au_lname" Type="String" />
          <asp:Parameter Name="address"  Type="String" />
          <asp:Parameter Name="city"     Type="String" />
          <asp:Parameter Name="state"    Type="String" />
          <asp:Parameter Name="zip"      Type="String" />
          <asp:Parameter Name="phone"    Type="String" />
          <asp:Parameter Name="contract" Type="Boolean" />
        </UpdateParameters>

      </asp:SqlDataSource>

      <asp:GridView ID="myGridView" DataSourceID="mySqlDataSource" runat="server"
        AutoGenerateColumns = "False"
        AllowPaging  = "True"
        AllowSorting = "True"
        DataKeyNames = "au_id"
        CellPadding  = "4"
        ForeColor    = "#333333"
        GridLines    = "None"
      >
        <Columns>
          <asp:BoundField    HeaderText="ID"         DataField="au_id"    SortExpression="au_id"    ReadOnly="True" />
          <asp:BoundField    HeaderText="First Name" DataField="au_fname" SortExpression="au_fname" />
          <asp:BoundField    HeaderText="Last Name"  DataField="au_lname" SortExpression="au_lname" />
          <asp:BoundField    HeaderText="Address"    DataField="address"  SortExpression="address" />
          <asp:BoundField    HeaderText="City"       DataField="city"     SortExpression="city" />
          <asp:BoundField    HeaderText="State"      DataField="state"    SortExpression="state" />
          <asp:BoundField    HeaderText="Zip Code"   DataField="zip"      SortExpression="zip" />
          <asp:BoundField    HeaderText="Phone"      DataField="phone"    SortExpression="phone" />
          <asp:CheckBoxField HeaderText="Contract"   DataField="contract" SortExpression="contract" />
          <asp:CommandField
            ButtonType       = "Button"
            ShowEditButton   = "True"
            ShowDeleteButton = "True"
          />

        </Columns>
        <HeaderStyle         BackColor="#333399" ForeColor="#FFFFFF" Font-Bold="True" />
        <RowStyle            BackColor="#CCCCCC" />
        <AlternatingRowStyle BackColor="#FFFFFF" />
        <PagerStyle          BackColor="#333399" ForeColor="#FFFFFF" HorizontalAlign="Center" />
      </asp:GridView>

    </form>

    </body>
    </html>

    Since we're now going to be manipulating the data in the GridView, we need to tell it which field contains the unique identifier for the table. In this case it's the author id field -- au_id. To do this, we use the DataKeyNames property and set it to the name of the table's primary key. I've also made that field read only since it's not something that should generally be changed.

    The final step is simply to tell the GridView to display the edit and delete buttons. We do this by adding a CommandField to the list of the GridView's columns. If you check the code listing above, you'll see that I've told it to show the edit and delete buttons and to display them as actual buttons instead of as the default text links.

    That's all there is to it. If we view the resulting page in a browser, it'll look something like this.

    Clicking on an edit button turns the editable fields into controls appropriate to the data type (in this case textboxes and a checkbox) and provides update and cancel buttons which allow the user to either commit the changes to the database or discard them.

    And one final thing to note is that since we set it as read only, the author id field is indeed unable to be edited.

    Filtering Data in the GridView Control

    Another popular requirement when dealing with data is the ability to simply look at a smaller set of it. For example, if you're going to be in California for a week, you might want to see a list of all the authors in California to see if any of them are available for a meeting. While doing this you probably don't care about authors located in Maryland or Indiana and including their names in the list might lead to you accidentally making an embarrassing phone call. In this case, you'd want to see a list of authors filtered by state.

    While you could easily build a page that filtered authors based on a state the user typed in, why should the user have to type anything in? We already know every state we have authors in and having a user type in data unnecessarily can only lead to problems. For this example, we're going to populate a DropDownList with all the available states and then when the user selects a state we'll filter the results displayed in the GridView to only show authors from that state.

    The first step is to populate our DropDownList with a list of available states. In order to do this we'll need another date source to retrieve the list of states. It uses the same connection string, but the SelectCommand now returns a list of unique states ordered alphabetically. I've set the DropDownList control to use this as it's data source and I've enabled AutoPostBack so that whenever the users selects a new state, that info is automatically sent back to the server and the page is refreshed with the authors for the new state.

    <%@ Page Language="VB" %>
    <html>
    <head>
      <title>Introducing the ASP.NET 2.0 GridView - Filtering</title>
    </head>
    <body>

    <form runat="server">

      <asp:SqlDataSource ID="myFilteringDataSource" runat="server"
        ConnectionString="Server=(local);Database=pubs;User Id=sa;Password=password;"
        SelectCommand="SELECT DISTINCT state FROM authors ORDER BY state"
      />

      Only Show Authors From:
      <asp:DropDownList ID="myDropDownList" runat="server"
        DataSourceID   = "myFilteringDataSource"
        DataValueField = "state"
        AutoPostBack   = "True"
      />


      <asp:SqlDataSource ID="mySqlDataSource" runat="server"
        ConnectionString = "Server=(local);Database=pubs;User Id=sa;Password=password;"
        SelectCommand = "SELECT * FROM authors WHERE state = @state"
      >
        <SelectParameters>
          <asp:ControlParameter Name="state" ControlID="myDropDownList" PropertyName="SelectedValue" />
        </SelectParameters>

      </asp:SqlDataSource>

      <asp:GridView ID="myGridView" DataSourceID="mySqlDataSource" runat="server"
        AllowPaging  = "True"
        AllowSorting = "True"
      />

    </form>

    </body>
    </html>

    The second step is to change the select command of the SQLDataSource control attached to the GridView so that it uses the value from the DropDownList to filter the list of authors returned. This is done by simply adding a where clause to our SQL query. Just like in the editing example, this clause requires a parameter. The big difference is that this time the parameter is coming from a control -- specifically our DropDownList. Notice that this is all done via declarative controls and properties. We still haven't had to write any actual code!

    When we first run the page California (CA) is selected simply because it's the first state in the list. Notice that only the records where the author's address is in California are shown.

    If we change the selected state to Utah (UT), the page refreshes and now only shows authors from Utah.

    Download the Code

    You can download the code in zip file format from here.

    Conclusion

    In the first part of this article we saw how easy the new ASP.NET 2.0 GridView control made displaying data on a web page. Even things that used to be complex are now quite simple. Even adding sorting and paging capabilities are as easy as flipping a switch.

    In this part, I've focused more on manipulating the data then just displaying it in a table, and I hope I've conveyed just how simple this can be as well. The new ASP.NET 2.0 data controls really do make handling data easier then it's ever been before. I've focused on the GridView simply because it's the natural successor to the ASP.NET 1.x DataGrid that most of us are familiar with, but it's not alone. The other controls are just as powerful and easy to use and I hope you'll give them a try soon.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 21, 2005 - N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005 - Part 1
    While the .NET Framework made building ASP.NET applications easier then it had ever been in the past, .NET 2.0 builds on that foundation in order to take things to the next level. This article shows you to how to construct an N-Tier ASP.NET 2.0 Web application by leveraging the new features of ASP.NET 2.0 and SQL Server 2005.
    [Read This Article]  [Top]
    Apr 28, 2005 - New Files and Folders in ASP.NET 2.0
    With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
    [Read This Article]  [Top]
    Mar 10, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2, Cont'd
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 9, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 3, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1, Cont'd
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Mar 2, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Feb 16, 2005 - Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
    In ASP.NET 2.0 and Visual Studio 2005, you can quickly program custom authentication pages with the provided Membership Login controls. In this article, Dina Fleet Berry examines the steps involved in using the Login control with a custom SQL Server membership database.
    [Read This Article]  [Top]
    Dec 29, 2004 - ClickOnce Deployment in .NET Framework 2.0
    In this article, Thiru Thangarathinam examines .NET 2.0's new ClickOnce deployment technology that is designed to ease deployment of Windows forms applications. This new technology not only provides an easy application installation mechanism, it also eases deployment of upgrades to existing applications.
    [Read This Article]  [Top]
    Dec 15, 2004 - A Sneak Peek at ASP.NET 2.0's Administrative Tools
    With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
    [Read This Article]  [Top]
    Nov 17, 2004 - The ASP.NET 2.0 TreeView Control
    Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    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: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    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