ObjectDataSource.ObjectCreating Event

Definition

Occurs before the object that is identified by the TypeName property is created.

public:
 event System::Web::UI::WebControls::ObjectDataSourceObjectEventHandler ^ ObjectCreating;
public event System.Web.UI.WebControls.ObjectDataSourceObjectEventHandler ObjectCreating;
member this.ObjectCreating : System.Web.UI.WebControls.ObjectDataSourceObjectEventHandler 
Public Custom Event ObjectCreating As ObjectDataSourceObjectEventHandler 

Event Type

Examples

This section contains two code examples. The first code example demonstrates how to use an ObjectDataSource object with a business object and a GridView control to display information. The second code example provides the middle-tier business object that is used in the first code example.

The following code example demonstrates how to use an ObjectDataSource control with a business object and a GridView control to display information. You might work with a business object that is very expensive to create (in terms of time or resources) for every data operation your Web page performs. One way to work with an expensive object might be to create an instance of it once, and then cache it for subsequent operations instead of creating and destroying it for every data operation.

Note

In a production application, multiple requests might end up simultaneously using the same instance. Therefore, the object needs to be implemented in a thread-safe manner.

This code example demonstrates this pattern. You can handle the ObjectCreating event to check the cache for an object first, and only create an instance of the object, if one is not already cached. Then, handle the ObjectDisposing event to cache the business object for future use, instead of destroying it. In this code example, the CancelEventArgs.Cancel property of the ObjectDataSourceDisposingEventArgs object is set to true to direct the ObjectDataSource to not call Dispose method on the object.

<%@ Import namespace="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

// Instead of creating and destroying the business object each time, the 
// business object is cached in the ASP.NET Cache.
private void GetEmployeeLogic(object sender, ObjectDataSourceEventArgs e)
{
    // First check to see if an instance of this object already exists in the Cache.
    EmployeeLogic cachedLogic;
    
    cachedLogic = Cache["ExpensiveEmployeeLogicObject"] as EmployeeLogic;
    
    if (null == cachedLogic) {
            cachedLogic = new EmployeeLogic();            
    }
        
    e.ObjectInstance = cachedLogic;     
}

private void ReturnEmployeeLogic(object sender, ObjectDataSourceDisposingEventArgs e)
{    
    // Get the instance of the business object that the ObjectDataSource is working with.
    EmployeeLogic cachedLogic = e.ObjectInstance as EmployeeLogic;        
    
    // Test to determine whether the object already exists in the cache.
    EmployeeLogic temp = Cache["ExpensiveEmployeeLogicObject"] as EmployeeLogic;
    
    if (null == temp) {
        // If it does not yet exist in the Cache, add it.
        Cache.Insert("ExpensiveEmployeeLogicObject", cachedLogic);
    }
    
    // Cancel the event, so that the object will 
    // not be Disposed if it implements IDisposable.
    e.Cancel = true;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:gridview
          id="GridView1"
          runat="server"          
          datasourceid="ObjectDataSource1">
        </asp:gridview>

        <asp:objectdatasource 
          id="ObjectDataSource1"
          runat="server"          
          selectmethod="GetCreateTime"          
          typename="Samples.AspNet.CS.EmployeeLogic"
          onobjectcreating="GetEmployeeLogic"
          onobjectdisposing="ReturnEmployeeLogic" >
        </asp:objectdatasource>        

    </form>
  </body>
</html>
<%@ Import namespace="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

' Instead of creating and destroying the business object each time, the 
' business object is cached in the ASP.NET Cache.
Sub GetEmployeeLogic(sender As Object, e As ObjectDataSourceEventArgs)

    ' First check to see if an instance of this object already exists in the Cache.
    Dim cachedLogic As EmployeeLogic 
    
    cachedLogic = CType( Cache("ExpensiveEmployeeLogicObject"), EmployeeLogic)
    
    If (cachedLogic Is Nothing) Then
            cachedLogic = New EmployeeLogic            
    End If
        
    e.ObjectInstance = cachedLogic
    
End Sub ' GetEmployeeLogic

Sub ReturnEmployeeLogic(sender As Object, e As ObjectDataSourceDisposingEventArgs)
    
    ' Get the instance of the business object that the ObjectDataSource is working with.
    Dim cachedLogic  As EmployeeLogic  
    cachedLogic = CType( e.ObjectInstance, EmployeeLogic)
    
    ' Test to determine whether the object already exists in the cache.
    Dim temp As EmployeeLogic 
    temp = CType( Cache("ExpensiveEmployeeLogicObject"), EmployeeLogic)
    
    If (temp Is Nothing) Then
        ' If it does not yet exist in the Cache, add it.
        Cache.Insert("ExpensiveEmployeeLogicObject", cachedLogic)
    End If
    
    ' Cancel the event, so that the object will 
    ' not be Disposed if it implements IDisposable.
    e.Cancel = True
End Sub ' ReturnEmployeeLogic
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - VB Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:gridview
          id="GridView1"
          runat="server"          
          datasourceid="ObjectDataSource1">
        </asp:gridview>

        <asp:objectdatasource 
          id="ObjectDataSource1"
          runat="server"          
          selectmethod="GetCreateTime"          
          typename="Samples.AspNet.VB.EmployeeLogic"
          onobjectcreating="GetEmployeeLogic"
          onobjectdisposing="ReturnEmployeeLogic" >
        </asp:objectdatasource>        

    </form>
  </body>
</html>

The following code example provides the example middle-tier business object that the preceding code example uses. The code example consists of a basic business object, defined by the EmployeeLogic class, which is a stateful class that encapsulates business logic. For a complete working example, you must compile this code as a library and use these classes from an ASP.NET page (.aspx file).

namespace Samples.AspNet.CS {

using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
  //
  // EmployeeLogic is a stateless business object that encapsulates
  // the operations you can perform on a NorthwindEmployee object.
  //
  public class EmployeeLogic {

    public EmployeeLogic () : this(DateTime.Now) {        
    }
    
    public EmployeeLogic (DateTime creationTime) { 
        _creationTime = creationTime;
    }

    private DateTime _creationTime;
    
    // Returns a collection of NorthwindEmployee objects.
    public ICollection GetCreateTime () {
      ArrayList al = new ArrayList();
      
      // Returns creation time for this example.      
      al.Add("The business object that you are using was created at " + _creationTime);
      
      return al;
    }
  }
}
Imports System.Collections
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.VB

  Public Class EmployeeLogic
    
    
    Public Sub New() 
        MyClass.New(DateTime.Now)
    
    End Sub
    
    
    Public Sub New(ByVal creationTime As DateTime) 
        _creationTime = creationTime
    
    End Sub
    
    Private _creationTime As DateTime
    
    
    ' Returns a collection of NorthwindEmployee objects.
    Public Function GetCreateTime() As ICollection 
        Dim al As New ArrayList()
        
        ' Returns creation time for this example.      
        al.Add("The business object that you are using was created at " + _creationTime)
        
        Return al
    
    End Function 'GetCreateTime
  End Class
End Namespace ' Samples.AspNet.VB

Remarks

If the method that is identified to perform the data operation is static (Shared in Visual Basic), the ObjectCreating and ObjectCreated events are never raised.

The ObjectDataSource control automatically calls the parameterless constructor of a business object to create an instance of it using reflection. Handle the ObjectCreating event to explicitly call another constructor, and set the instance of the object that results to the ObjectInstance property of the associated ObjectDataSourceEventArgs object.

For more information about how to handle events, see Handling and Raising Events.

Applies to

See also