Adding Event-Handling Code

IOTA^_^    

ASP.NET Developer's JumpStart
By Paul D. Sheriff, Ken Getz
Table of Contents
Chapter 19.  Using the DataList Control


Your page is all laid out, and the DataGrid control contains both its ItemTemplate and EditItemTemplate sections, but you won't be able to edit or update data yet you must add code to handle the EditCommand, UpdateCommand, and CancelCommand events raised by the control. When you click the Edit button on the page, the DataList control raises its EditCommand event (and your code can react to that event). The same applies to the Update and Cancel buttons, triggering the UpdateCommand and CancelCommand events, respectively.

When you click the Edit button, you trigger a postback to the page. Back on the server, you need to somehow indicate to the DataList control that it's now in "edit" mode and it should display its EditItemTemplate for the selected row.

With the EditItemTemplate displayed, if you click Update, you need to have the data saved back to its source. If you click Cancel, you need to abandon the edit. In either case, you need to post back to the page and somehow indicate to the control that it should display the current row using its ItemTemplate (or AlternatingItemTemplate, if you supplied this template).

TIP

To specify that you want to display a row using the EditItemTemplate, all you need to do is set the EditItemIndex to a value other than -1. You specify the ordinal value corresponding to the item you want to edit, and the control takes care of the rest. To indicate that you want to display the Item/AlternatingItemTemplate, set the EditItemIndex property to -1 again.


In order to complete your page, follow these steps, adding the appropriate event handlers:

  1. Use the View, Code menu item to display the page's code-behind file.

  2. From the Class Name drop-down list (the list on the left) at the top of the code editor, select datEmps. From the Method Name list (the list on the right), select EditCommand. This inserts the stub for the datEmps_EditCommand event handler into the module.

  3. Modify the new procedure so that it looks like this:

     Private Sub datEmps_EditCommand( _  ByVal source As System.Object, _  ByVal e As System.Web.UI.WebControls. _  DataListCommandEventArgs) _  Handles datEmps.EditCommand   datEmps.EditItemIndex = e.Item.ItemIndex   DataListBind() End Sub 
  4. Repeat the previous two steps, this time modifying the datEmps_CancelCommand procedure:

     Private Sub datEmps_CancelCommand( _  ByVal source As System.Object, _  ByVal e As System.Web.UI.WebControls. _  DataListCommandEventArgs) _  Handles datEmps.CancelCommand   datEmps.EditItemIndex = -1   DataListBind() End Sub 
  5. Repeat the previous two steps, modifying the datEmps_UpdateCommand procedure as shown in Listing 19.2.

    TIP

    Rather than typing this entire procedure, you can copy and paste it in from the Jumpstart\DataList\UpdateCommand.txt file.

    Listing 19.2 Update Data Using the UpdateCommand Event Handler
     Private Sub datEmps_UpdateCommand( _  ByVal source As System.Object, _  ByVal e As System.Web.UI.WebControls. _  DataListCommandEventArgs) _  Handles datEmps.UpdateCommand   Dim strSQL As String   Dim strConn As String   Dim strFirstName As String   Dim strLastName As String   Dim strPhone As String   ' Retrieve values from e.Item   strLastName = GetControlText(e.Item, "txtLastName")   strFirstName = GetControlText(e.Item, "txtFirstName")   strPhone = GetControlText(e.Item, "txtPhone")   ' Build up the SQL string. Be careful about   ' embedded apostrophes! That's what the QuoteString   ' method is for.   strSQL = String.Format( _    "UPDATE Employees " & _    "SET FirstName = {0}, LastName = {1}, " & _    "HomePhone = {2} " & _    "WHERE EmployeeID = {3}", _    DataHandler.QuoteString(strFirstName), _    DataHandler.QuoteString(strLastName), _    DataHandler.QuoteString(strPhone), _    e.CommandArgument.ToString)   ' Build Connection String   strConn = Session("ConnectString").ToString   Try     ' Submit the SQL     DataHandler.ExecuteSQL(strSQL, strConn)   Catch exp As Exception     lblError.Text = exp.Message   End Try   ' Cancel the edit mode.   datEmps.EditItemIndex = -1   ' Reload employee info. You can't simply   ' rebind to the stored Session variable--   ' its data is now incorrect.   DataListLoad()   DataListBind() End Sub 
  6. This procedure is somewhat complex and requires some investigation. The datEmps_UpdateCommand procedure takes these actions when you click the Update link on the DataList control:

    • It retrieves the text from the three TextBox controls on the EditItemTemplate. This in itself requires a little explanation: Your event-handling procedure receives, as its parameter, the value e, which contains information about the DataList control that triggered the event. The Item property of the object provides a reference to the active template, and you must somehow find the controls you need within this template. You can either refer to the controls by their ordinal position within the template (by number) or use the FindControl method to find the control you need, by name. We've used this technique here, and the GetControlText function (see the next step) calls the FindControl method for you and returns the value in the text box you request:

       ' Retrieve values from e.Item strLastName = GetControlText(e.Item, "txtLastName") strFirstName = GetControlText(e.Item, "txtFirstName") strPhone = GetControlText(e.Item, "txtPhone") 

      NOTE

      If you're paying attention, you may remember that we wrote very similar code in Chapter 16, "Using the DataGrid Control." In that case, however, we used the other technique we simply used the ordinal value of the control we needed to find within the EditItemTemplate for the DataGrid control. Why handle this differently here? In the case of the DataGrid control, there were only two controls in the EditItemTemplate, and it was easy to determine the ordinal position of each within the template. In this case, there are a number of controls in the template, and it's risky to count on the particular position of any one control within the template. Although it's more effort, the FindControl method is safer it doesn't depend on any hard-coded ordinal values.

    • It builds the required SQL UPDATE statement, filling in values retrieved from the EditItemTemplate:

       strSQL = String.Format( _  "UPDATE Employees " & _  "SET FirstName = {0}, LastName = {1}, " & _  "HomePhone = {2} " & _  "WHERE EmployeeID = {3}", _  DataHandler.QuoteString(strFirstName), _  DataHandler.QuoteString(strLastName), _  DataHandler.QuoteString(strPhone), _  e.CommandArgument.ToString) 
    • It retrieves the connection string from the Session variable:

       ' Build Connection String   strConn = Session("ConnectString").ToString 
    • It calls the ExecuteSQL method you've seen throughout this book:

       ' Submit the SQL DataHandler.ExecuteSQL(strSQL, strConn) 
    • It cancels "edit" mode and then rebinds and reloads the DataList control's data source:

       ' Cancel the edit mode. datEmps.EditItemIndex = -1 ' Reload employee info. You can't simply ' rebind to the stored Session variable-- ' its data is now incorrect. DataListLoad() DataListBind() 
  7. To finish, add the following procedure to the class:

     Private Function GetControlText( _  ByVal Item As WebControl, _  ByVal ControlName As String) As String   ' This method will fail if you pass it a control   ' that doesn't exist. But that shouldn't happen, since   ' you created the controls.   Return CType(Item.FindControl(ControlName), _    TextBox).Text End Function 

The GetControlText procedure uses the FindControl method (given a control name), casts the resulting control as a text box, and calls its Text property to retrieve the results.

At this point, you've added all the functionality your page requires. Take a few moments and verify that you can view employees, edit the data, and either save or cancel the changes.

TIP

There's no reason you couldn't add functionality that would allow you to add or delete employees, using this same page. Deleting an employee would simply require adding a Delete link to the EditItemTemplate and then adding code to handle the DeleteCommand event of the control. You could model this code on the UpdateCommand code, although it would be much simpler. To add a new employee, you could place an Add link on the page (not on the DataList control) that could navigate to a page on which you could enter information about a new employee. The code to do all this would be quite similar to the corresponding code on the ProductsEdit.aspx page, as discussed in Chapter 17, "Editing Data Using the DataGrid Control."



    IOTA^_^    
    Top


    ASP. NET Developer's JumpStart
    ASP.NET Developers JumpStart
    ISBN: 0672323575
    EAN: 2147483647
    Year: 2002
    Pages: 234

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net