Share via


Creating an ObjectDataSource Control Source Object

The source object for an ObjectDataSource control retrieves data and performs updates in the underlying data source as requested by the ObjectDataSource control. The source object for an ObjectDataSource control can be any class that the ObjectDataSource control can create an instance of, or that exposes public static (Shared in Microsoft Visual Basic) methods that the ObjectDataSource control can call.

For an example of a source object and the ASP.NET page that includes an ObjectDataSource control that uses the source object, see ObjectDataSource Source Object Example or ObjectDataSource Strongly Typed Source Object Example.

Object Creation

The ObjectDataSource control will create an instance of the source object, call the specified method, and dispose of the object instance all within the scope of a single request, if your object has instance methods instead of static methods (Shared in Visual Basic). Therefore, your object must be stateless. That is, your object should acquire and release all required resources within the span of a single request.

You can control how the source object is created by handling the ObjectCreating event of the ObjectDataSource control. You can create an instance of the source object, and then set the ObjectInstance property of the ObjectDataSourceEventArgs class to that instance. The ObjectDataSource control will use the instance that is created in the ObjectCreating event instead of creating an instance on its own.

Specifying a Class Constructor

If the source object for an ObjectDataSource control exposes public static methods (Shared in Visual Basic) that can be called to retrieve and modify data, an ObjectDataSource control will call those methods directly. If an ObjectDataSource control must create an instance of the source object in order to make method calls, the object must include a public constructor that takes no parameters. The ObjectDataSource control will call this constructor when it creates a new instance of the source object.

If the source object does not contain a public constructor without parameters, you can create an instance of the source object that will be used by the ObjectDataSource control in the ObjectCreating event, as discussed in "Object Creation," earlier in this topic.

Specifying Object Methods

The source object for an ObjectDataSource control can contain any number of methods that are used to select, insert, update, or delete data. These methods are called by the ObjectDataSource control based on the name of the method, as identified by using either the SelectMethod, InsertMethod, UpdateMethod, or DeleteMethod property of the ObjectDataSource control and the names of the parameters that are in the related parameter collection for the selected action. For detailed information, see Using Parameters with the ObjectDataSource Control.

The source object can also include an optional SelectCount method, which is identified by the ObjectDataSource control using the SelectCountMethod property, that returns the count of the total number of objects at the data source. The ObjectDataSource control will call the SelectCount method after a Select method has been called to retrieve the total number of records at the data source for use when paging.

Note

It is strongly recommended that you implement a SelectCount method if your object supports paging. This will minimize the number of records that a data-bound control, such as the GridView control, must request to retrieve a page of data. If the total row count is supplied by the source data object, a data-bound control will request only a single page of rows at a time for each page. If the total row count is not supplied, a data-bound control must request all rows from the data source (starting with the first row of the requested page of data) and discard any rows that are not in the current page.

Working with Strongly Typed Objects

Your source object can return and receive strongly typed objects based on the data from your data source. The ObjectDataSource control identifies the type of these objects using the DataObjectTypeName property. In this scenario, instead of passing one or more parameters to a method, one object is passed that aggregates all parameter values. For more information about how to pass a specific object type as a parameter for a source object method, see Using Parameters with the ObjectDataSource Control.

When the ConflictDetection property of an ObjectDataSource control is set to the CompareAllValues value, and the OldValuesParameterFormatString property is set to a value that distinguishes parameters for original values from parameters for current values, the ObjectDataSource will do the following:

  • Call the Update method from the source object that takes parameters for both current and original values.

  • Call the Delete method from the source object that takes parameters for original values.

When it uses a strongly typed object, the ObjectDataSource control will call the Update method from the source object that takes both a strongly typed object that is populated with current values and a strongly typed object that is populated with original values. However, when the ObjectDataSource control calls the Delete method and passes a strongly typed object, it calls the method that takes a single strongly typed object as a parameter, regardless of the ConflictDetection or OldValuesParameterFormatString setting. If the ConflictDetection property is set to the OverwriteChanges value, the object that is passed to the Delete method is populated with current primary key values only (the other properties of the object are null). If the ConflictDetection property is set to the CompareAllValues value, the object that is passed to the Delete method is populated with original primary key values and original values for the rest of the object properties.

Working with Designers

Optionally, you can apply attributes to your source object that describe it to a designer, such as the Microsoft Visual Web Developer Web development tool, as a data object. This can improve the experience of the developer who is using the designer by specifically identifying which methods of your object are used for select, insert, update, and delete operations.

To identify your object as a source object for an ObjectDataSource control, use the DataObjectAttribute attribute, as shown in the following example.

<DataObject(True)> _
Public Class NorthwindEmployee 
[DataObject(true)]
public class NorthwindEmployee

To identify a method as a data object method, use the DataObjectMethodAttribute attribute. When you apply the DataObjectMethodAttribute attribute, include one of the DataObjectMethodType enumeration values to identify the type of method (either select, insert, update, or delete). The following code example uses the DataObjectMethodAttribute attribute to identify a method as a Delete method.

<DataObjectMethod(DataObjectMethodType.Delete)> _
Public Shared Function DeleteEmployee(EmployeeID As Integer) As Boolean

  If Not _initialized Then Initialize()

  Dim conn As SqlConnection  = New SqlConnection(_connectionString)
  Dim cmd  As SqlCommand     = New SqlCommand("DELETE FROM Employees WHERE EmployeeID = @EmployeeID", conn)  
  cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID

  Try
    conn.Open()

    If cmd.ExecuteNonQuery() <> 0 Then _
      Return False
  Catch e As SqlException
    ' Handle exception.
  Finally
    conn.Close()
  End Try

  Return True
End Function
[DataObjectMethod(DataObjectMethodType.Delete)]
public static bool DeleteEmployee(int EmployeeID)
{
  if (!_initialized) { Initialize(); }

  SqlConnection conn = new SqlConnection(_connectionString);
  SqlCommand    cmd  = new SqlCommand("DELETE FROM Employees WHERE EmployeeID = @EmployeeID", conn);  
  cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID;

  try
  {
    conn.Open();

    if (cmd.ExecuteNonQuery() == 0)
      return false;
  }
  catch (SqlException e)
  {
    // Handle exception.
  }
  finally
  {
    conn.Close();
  }

  return true;
}

See Also

Concepts

ObjectDataSource Source Object Example

Using Parameters with the ObjectDataSource Control

Reference

ObjectDataSource Web Server Control Overview