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, September 4, 2002

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


The Eighth Part in a Multi-Part Series
This article is the eighth piece of a multi-part series on using the DataGrid Web control that will span several months. 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 Part 4 we looked at how to extend Part 3 to provide custom sorting on the results of a DataGrid. In Part 5 we examined how to use templates to further customize the DataGrid's appearance. Part 6 examined how to use the DataGrid's built-in editing capabilities, while Part 7 looked at customizing the editing interface using the EditItemTemplate. In this part we will look at how to add client-side code to a ButtonColumn's client-side onclick event.

- continued -

  • 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
  • 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
    In Part 6 in this article series we examined how the DataGrid could be utilized to provide in-place editing of data. In addition to allowing a user to edit data, one may want to allow the user to delete data. This can be accomplished by adding a ButtonColumn control that contains a Delete button, which will add a Delete button to each row of the DataGrid. When a user clicks the Delete button for a particular row, that row will then be deleted from the database.

    To accomplish this we have to perform the following tasks:

    1. Create a ButtonColumn that contains a Delete button.
    2. Somehow be able to determine when the Delete button has been clicked and have some server-side code ready to execute.
    3. Be able to determine the primary key field value for the row whose Delete button has been clicked. We need to primary key field value so that we can issue a SQL statement to delete the selected row.

    In addition to examining how to accomplish the above three steps, this article will also look at how to add a client-side confirm dialog box to the Delete button. That is, when a user clicks the Delete button a client-side messagebox will appear, asking the user if they are sure if they want to delete the item. If they click OK, the row will be deleted; if they click cancel, nothing will happen.

    Creating a Delete Button
    In Part 3 of this article series we examined how to add ButtonColumns to a DataGrid Web control. Recall from Part 3 that any time a DataGrid's ButtonColumn button is clicked by the user, the ASP.NET Web page performs a postback and the DataGrid's ItemCommand event is raised. While we could place our delete code in the ItemCommand event handler, the DataGrid control offers a special event handler for delete buttons: the DeleteCommand event handler.

    In order to create a ButtonColumn that triggers the DeleteCommand event handler you must set the ButtonColumn's CommandName property to "Delete". Once you do this, you will want to create an event handler for the DeleteCommand event. This event handler takes the form:

    Sub eventHandlerName(sender as Object, e as DataGridCommandEventArgs)
       ...
    End Sub

    In this event handler we'll (eventually) place the code to make a database call to delete the specified DataGrid item. Finally, to complete the last piece of the puzzle we must tell the DataGrid that when the DeleteCommand event fires the event handler (eventHandlerName) should be executed. We do this by setting the DataGrid's OnDeleteCommand property to the event handler in the DataGrid's declaration like so: OnDeleteCommand="eventHandlerName".

    Below you can see a simple example that illustrates adding a Delete button to a DataGrid, adding an event handler for the DeleteCommand event, and wiring up this event handler to the DataGrid's DeleteCommand event:

    <script language="vb" runat="server">
      ...
    
      Sub dgPopularFAQs_Delete(sender As Object, e As DataGridCommandEventArgs)
        ' Place code to perform delete here...
      End Sub
    </script>
    
    <form runat="server">
      <asp:datagrid id="dgPopularFAQs" runat="server"
      	  ...
          OnDeleteCommand="dgPopularFAQs_Delete">
    	
        <Columns>
      	<asp:ButtonColumn Text="Delete" CommandName="Delete" />
      	<asp:BoundColumn DataField="FAQID" HeaderText="FAQ ID"
      	     ItemStyle-HorizontalAlign="Center" />
      	<asp:BoundColumn DataField="Description" HeaderText="Question" />
        </Columns>	
      </asp:datagrid>
    </form>
    
    [View a Live Demo!]

    It is important to set the ButtonColumn's CommandName property to "Delete", otherwise the DataGrid's DeleteCommand event won't fire when the command button is clicked. (Rather, just the DataGrid's ItemCommand event will fire.) Also note that in order to have the dgPopularFAQs_Delete event handler execute when the DataGrid's DeleteCommand event fires we had to specify OnDeleteCommand="dgPopularFAQs_Delete" in the DataGrid's declaration.

    Determining the Clicked Row's Primary Key Field Value
    In order to issue a database command to delete the selected item from the DataGrid, we must be able to uniquely identify the selected item. Usually this takes the form of a numeric primary key field. In the live demos for this article, we're using the ASPFAQs.com database, and the primary key for each FAQ is a database field called FAQID.

    In Part 3 we looked at one method for retrieving a primary key field value, which involved using a hidden BoundColumn and then referencing the value of the BoundColumn programmatically in the ItemCommand event handler. We could use this approach here as well, since we already have a BoundColumn displaying the FAQID. However, let's use a more elegant approach.

    The DataGrid control contains a DataKeyField property. This optional property can be used to specify the primary key field for the data being displayed in the DataGrid. If this property is set, a separate DataGrid property, DataKeys (a collection), is populated with the primary key values for each row in the DataGrid. Hence, we can access this collection programmatically in our DeleteCommand event handler. To get the proper item out of the DataKeys collection, we simply reference the index that is equal to the clicked DataGrid row's ItemIndex. This concept is illustrated below:

    <script language="vb" runat="server">
      ...
    
      Sub dgPopularFAQs_Delete(sender As Object, e As DataGridCommandEventArgs)
        'Get the FAQID of the row whose Delete button was clicked
        Dim SelectedFAQID as String = dgPopularFAQs.DataKeys(e.Item.ItemIndex)
        
        'TODO: Delete the record from the database
        
        'TODO: Rebind the DataGrid
      End Sub
    </script>
    
    <form runat="server">
      <asp:datagrid id="dgPopularFAQs" runat="server"
      	  ...
          DataKeyField="FAQID">
    
        ...	
      </asp:datagrid>
    </form>
    
    [View a Live Demo!]

    In the live demo you can see that when clicking a Delete button we can ascertain the row's corresponding FAQID. We could have used the techniques learned in Part 3 in order to retrieve the value of the FAQID BoundColumn, but, personally, I find using the DataKeyField / DataKeys approach to be cleaner code.

    Now that we've examined how to add a Delete button to each row, and how to determine the primary key field value for the row whose Delete button was clicked, writing the code to make the actual database call to delete the record should be fairly simple, and therefore is left as an exercise for the reader. The one thing that is important is to remember to recompute the DataGrid's DataSource and call the DataGrid's DataBind() method. This is needed because the DataSource has changed (a row has been deleted).

    Before we wrap up this article, let's take a look at how to add some client-side confirmation code for the Delete button. That is, when the user clicks the Delete button for a row in the DataGrid, let's have a client-side messagebox pop up, asking the user if they're sure they want to delete the record. If they click Cancel, the record won't be deleted; if they click OK, however, the record will be deleted. We'll see how to do this in Part 2.

  • 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