Handling ObjectDataSource Control Events


Handling ObjectDataSource Control Events

The ObjectDataSource control supports the following events:

  • Deleting Occurs immediately before the method represented by the DeleteMethod property is called

  • Deleted Occurs immediately after the method represented by the DeleteMethod property is called

  • Inserting Occurs immediately before the method represented by the InsertMethod property is called

  • Inserted Occurs immediately after the method represented by the InsertMethod property is called

  • Selecting Occurs immediately before the method represented by the SelectMethod property is called

  • Selected Occurs immediately after the method represented by the InsertMethod property is called

  • Updating Occurs immediately before the method represented by the InsertMethod property is called

  • Updated Occurs immediately after the method represented by the InsertMethod property is called

  • Filtering Occurs immediately before the filter expression is evaluated

  • ObjectCreating Occurs immediately before the object represented by the ObjectDataSource control is created

  • ObjectCreated Occurs immediately after the object represented by the ObjectDataSource control is created

  • ObjectDisposing Occurs before the object represented by the ObjectDataSource control is destroyed

Notice that most of these events come in pairs. One event happens immediately before a method is called, and one event happens immediately after a method is called.

You can handle these events to modify the parameters and objects represented by an ObjectDataSource control. You can also handle these events to handle any errors that might result from calling methods with the ObjectDataSource control.

Adding and Modifying Parameters

You can handle the Selecting, Inserting, Updating, and Deleting events to modify the parameters that are passed to the methods called by the ObjectDataSource control. There are several situations in which you might want to do this.

First, if you are working with an existing component, you might need to change the names of the parameters passed to the component. For example, instead of passing a parameter named id to an update method, you might want to rename the parameter to movieId.

Second, you might want to pass additional parameters to the method being called. For example, you might need to pass the current username, the current IP address, or the current date and time as a parameter to a method.

For example, imagine that you want to create a guestbook and automatically associate the IP address of the user making an entry with each entry in the guestbook. The page in Listing 15.29 illustrates how you can do this with the help of a FormView control and an ObjectDataSource control (see Figure 15.9).

Figure 15.9. Displaying a guestbook.


Listing 15.29. ShowGuestbook.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server">     Protected  Sub srcGuestbook_Inserting(ByVal sender As Object, ByVal e As  ObjectDataSourceMethodEventArgs)         e.InputParameters.Add("IPAddress", Request.UserHostAddress)     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head  runat="server">     <style type="text/css">         .guestbook td,.guestbook th         {             padding:5px;             font:14px Arial,Sans-Serif;         }     </style>     <title>Show Guestbook</title> </head> <body>     <form  runat="server">     <div>     <asp:FormView                  DataSource         DefaultMode="Insert"         Runat="server">         <InsertItemTemplate>         <asp:Label                          Text="Comment:"             AssociatedControl             Runat="server" />         <br />         <asp:TextBox                          Text='<%# Bind("comment") %>'             TextMode="MultiLine"             Columns="50"             Rows="4"             Runat="server" />         <br />         <asp:Button                          Text="Add Entry"             CommandName="Insert"             Runat="server" />         </InsertItemTemplate>     </asp:FormView>     <hr />     <asp:GridView                  DataSource         Css         Runat="server" />     <asp:ObjectDataSource                  TypeName="Guestbook"         SelectMethod="GetEntries"         InsertMethod="AddEntry"         OnInserting="srcGuestbook_Inserting"         Runat="server" />     </div>     </form> </body> </html> 

The page in Listing 15.29 includes an Inserting event handler. When the insert method is called, the IP address of the current user is added to the parameters collection.

The ObjectDataSource control in Listing 15.29 is bound to the Guestbook component in Listing 15.30.

Listing 15.30. Guestbook.vb

Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Web.Configuration Public Class Guestbook     Private _conString As String     Public Function GetEntries() As SqlDataReader         ' Initialize connection         Dim con As New SqlConnection(_conString)         ' Initialize command         Dim cmd As New SqlCommand()         cmd.Connection = con         cmd.CommandText = "SELECT Id,IPAddress,Comment,EntryDate FROM Guestbook"         ' Execute command         con.Open()         Return cmd.ExecuteReader(CommandBehavior.CloseConnection)     End Function     Public Sub AddEnTry(ByVal IPAddress As String, ByVal comment As String)         ' Initialize connection         Dim con As New SqlConnection(_conString)         ' Initialize command         Dim cmd As New SqlCommand()         cmd.Connection = con         cmd.CommandText = "INSERT Guestbook (IPAddress,Comment)" _             + " VALUES (@IPAddress, @Comment)"         ' Add ADO.NET parameters         cmd.Parameters.AddWithValue("@IPAddress", IPAddress)         cmd.Parameters.AddWithValue("@Comment", comment)         ' Execute command         Using con             con.Open()             cmd.ExecuteNonQuery()         End Using     End Sub     Public Sub New()         _conString = WebConfigurationManager.ConnectionStrings("Guestbook").ConnectionString     End Sub  End Class 

Realize that you can manipulate the parameters collection in any way that you need. You can change the names, types, or values of any of the parameters.

Handling Method Errors

You can handle the Selected, Inserted, Updated, or Deleted events in order to handle any errors that might result from calling a method. For example, the page in Listing 15.31 handles the Inserting event to capture any errors raised when the method represented by the ObjectDataSource control's InsertMethod property is called.

Listing 15.31. HandleErrors.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server">     Protected  Sub srcMovies_Inserted(ByVal sender As Object, ByVal e As  ObjectDataSourceStatusEventArgs)         If Not e.Exception Is Nothing Then             e.ExceptionHandled = True             lblError.Text = "Could not insert movie"         End If     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <style type="text/css">         html         {             background-color:silver;         }         .insertForm         {             background-color:white;         }         .insertForm td,.insertForm th         {             padding:10px;         }         .error         {             color:red;             font:bold 14px Arial,Sans-Serif;         }     </style>     <title>Handle Errors</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  EnableViewState="false"         Css         Runat="server" />     <h1>Insert Movie</h1>     <asp:DetailsView                  DataSource         DefaultMode="Insert"         AutoGenerateInsertButton="true"         AutoGenerateRows="false"         Css         GridLines="None"         Runat="server">         <Fields>         <asp:BoundField             DataField="Title"             HeaderText="Title:"/>         <asp:BoundField             DataField="Director"             HeaderText="Director:" />         </Fields>     </asp:DetailsView>     <asp:ObjectDataSource                  TypeName="InsertMovie"         InsertMethod="Insert"         Runat="server" OnInserted="srcMovies_Inserted" />     </div>     </form> </body> </html> 

In Listing 15.31, the Inserted event handler checks for an exception. If an exception exists, then the exception is handled and an error message is displayed (see Figure 15.10).

Figure 15.10. Handling method errors gracefully.


The page in Listing 15.31 is bound to the component in Listing 15.32.

Listing 15.32. InsertMovie.vb

Imports System Imports System.Web Imports System.Data Imports System.Data.SqlClient Imports System.Web.Configuration Public Class InsertMovie     Private Shared ReadOnly _conString As String     Public Shared Function GetMovies() As SqlDataReader         ' Initialize connection         Dim con As New SqlConnection(_conString)         ' Initialize command         Dim cmd As New SqlCommand()         cmd.Connection = con         cmd.CommandText = "SELECT Id,Title,Director FROM Movies"         ' Execute command         con.Open()         Return cmd.ExecuteReader(CommandBehavior.CloseConnection)     End Function     Public Shared Sub Insert(ByVal title As String, ByVal director As String)         ' Initialize connection         Dim con As New SqlConnection(_conString)         ' Initialize command         Dim cmd As New SqlCommand()         cmd.Connection = con         cmd.CommandText = "INSERT Movies (Title,Director)" _             + " VALUES (@Title,@Director)"         ' Add ADO.NET parameters         cmd.Parameters.AddWithValue("@Title", title)         cmd.Parameters.AddWithValue("@Director", director)         ' Execute command         Using con             con.Open()             cmd.ExecuteNonQuery()         End Using     End Sub     Shared Sub New()         _conString = WebConfigurationManager.ConnectionStrings("Movies").ConnectionString     End Sub  End Class 

You can create an exception by entering a new movie record and not supplying a value for one of the fields. For example, the Title column in the Movies database table does not accept null values.

Note

Instead of handling errors at the level of the DataSource control, you can handle errors at the level of the DataBound control. For example, the DetailsView control supports an ItemInserted event.


Handling the ObjectCreating Event

By default, the ObjectDataSource control can represent only components that have a constructor that does not require any parameters. If you are forced to use a component that does require parameters for its constructor, then you can handle the ObjectDataSource control's ObjectCreating event.

For example, the component in Listing 15.33 must be initialized with a movie category parameter. The component returns only movies in the specified category.

Listing 15.33. MoviesByCategory.vb

Imports System Imports System.Web Imports System.Data Imports System.Data.SqlClient Imports System.Web.Configuration Public Class MoviesByCategory     Private ReadOnly _conString As String     Private ReadOnly _movieCategory As String     Public Function GetMovies() As SqlDataReader         ' Initialize connection         Dim con As New SqlConnection(_conString)         ' Initialize command         Dim cmd As New SqlCommand()         cmd.Connection = con         cmd.CommandText = "SELECT Title,Director,DateReleased FROM Movies" _             + " JOIN MovieCategories ON Movies.CategoryId=MovieCategories.Id" _             + " WHERE MovieCategories.Name=@CategoryName"         ' Create ADO.NET parameters         cmd.Parameters.AddWithValue("@CategoryName", _movieCategory)         ' Execute command         con.Open()         Return cmd.ExecuteReader(CommandBehavior.CloseConnection)     End Function     Public Sub New(ByVal movieCategory As String)         _movieCategory = movieCategory         _conString = WebConfigurationManager.ConnectionStrings("Movies").ConnectionString     End Sub  End Class 

The page in Listing 15.34 contains an ObjectDataSource control that represents the MoviesByCategory component. The page includes a handler for the ObjectCreating event so that it can assign an initialized instance of the MoviesByCategory component to the ObjectDataSource control.

Listing 15.34. ShowAdventureMovies.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server">     Protected Sub srcMovies_ObjectCreating(ByVal sender As Object, ByVal e As  ObjectDataSourceEventArgs)         Dim movies As New MoviesByCategory("Adventure")         e.ObjectInstance = movies     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Adventure Movies</title> </head> <body>     <form  runat="server">     <div>     <h1>Adventure Movies</h1>     <asp:GridView                  DataSource         Runat="server" />     <asp:ObjectDataSource                  TypeName="MoviesByCategory"         SelectMethod="GetMovies"         OnObjectCreating="srcMovies_ObjectCreating"         Runat="server" />     </div>     </form> </body> </html> 

Notice that even though the MoviesByCategory component is initialized in the ObjectCreating event handler, you still must assign the name of the component to the ObjectDataSource control's TypeName property. The ObjectDataSource control needs to know what type of object it is representing when it calls its methods.

Note

The ObjectCreating event is not raised when a shared method is called.





ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

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