Export (0) Print
Expand All
9 out of 35 rated this helpful - Rate this topic

ObjectDataSource Class

Note: This class is new in the .NET Framework version 2.0.

Represents a business object that provides data to data-bound controls in multi-tier Web application architectures.

Namespace: System.Web.UI.WebControls
Assembly: System.Web (in system.web.dll)

public class ObjectDataSource : DataSourceControl
public class ObjectDataSource extends DataSourceControl
public class ObjectDataSource extends DataSourceControl

The ObjectDataSource is an ASP.NET data source control that represents a data-aware middle-tier object or a data-interface object to data-bound controls. You can use the ObjectDataSource control in conjunction with a data-bound control to display, edit, and sort data on a Web page with little or no code.

A very common application design practice is to separate the presentation layer from business logic and encapsulate the business logic in business objects. These business objects form a distinct layer between the presentation layer and the data tier, resulting in a three-tier application architecture. The ObjectDataSource control enables developers to use an ASP.NET data source control while retaining their three-tier application architecture.

The ObjectDataSource control uses reflection to create instances of business objects and to call methods on them to retrieve, update, insert, and delete data. The TypeName property identifies the name of the class that the ObjectDataSource works with. The ObjectDataSource control creates and destroys an instance of the class for each method call; it does not hold the object in memory for the lifetime of the Web request. This is a serious consideration if the business object that you use requires many resources or is otherwise expensive to create and destroy. Using an expensive object might not be an optimal design choice, but you can control the life cycle of the object using the ObjectCreating, ObjectCreated, and ObjectDisposing events.

NoteNote

The methods that are identified by the SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod properties can be instance methods or static (Shared in Visual Basic) methods. If the methods are static (Shared in Visual Basic), an instance of the business object is not created and the ObjectCreating, ObjectCreated, and ObjectDisposing events are not raised.

To retrieve data from a business object, set the SelectMethod property with the name of the method that retrieves data. If the method does not return an IEnumerable or DataSet object, the object is wrapped by the runtime in an IEnumerable collection. If the method signature has parameters, you can add Parameter objects to the SelectParameters collection, and then bind them to the values that you want to pass to the method that is specified by the SelectMethod method. In order for the ObjectDataSource to use the parameters, the parameters must match the names and types of the parameters in the method signature.

The ObjectDataSource control retrieves data whenever the Select method is called. This method provides programmatic access to the method that is specified by SelectMethod property. The method that is specified by the SelectMethod property is called automatically by controls that are bound to the ObjectDataSource when their DataBind method is called. If you set the DataSourceID property of a data-bound control, the control automatically binds to data from the data source, as needed. Setting the DataSourceID property is the recommended method for binding an ObjectDataSource control to a data-bound control. Alternatively, you can set the DataSource property, but then you must explicitly call the DataBind method of the data-bound control. You can call the Select method programmatically at any time to retrieve data.

For more information on binding data-bound controls to data source controls, see Binding to Data Using a Data Source Control.

Depending on the capabilities of the business object that the ObjectDataSource control works with, you can perform data operations, such as updates, inserts, and deletes. To perform these data operations, set the appropriate method name and any associated parameters for the operation that you want to perform. For example, for an update operation, set the UpdateMethod property to the name of the business object method that performs updates and add any required parameters to the UpdateParameters collection. If the ObjectDataSource control is associated with a data-bound control, the parameters are added by the data-bound control. In this case, you need to ensure that the parameters names of the method match the field names in the data-bound control. The update is performed when the Update method is called, either explicitly by your code or automatically by a data-bound control. The same general pattern is followed for Delete and Insert operations. Business objects are assumed to perform these types of data operations one record at a time, rather than batched.

The ObjectDataSource control can filter data that is retrieved by the SelectMethod property, if the data is returned as a DataSet, DataView, or DataTable object. The ObjectDataSource control allows you to cache all types of data, but you should not cache objects that retain resources or state that cannot be shared to service multiple requests (for example, an open SqlDataReader object), because this same instance of the object will be used to service multiple requests. You can set the FilterExpression property to a filtering expression using a format string syntax and bind values in the expression to parameters that are specified in the FilterParameters collection.

While the ObjectDataSource does not retain the instance of the business object across multiple requests, it can cache the result of the SelectMethod method. While the data is cached, subsequent calls to the Select method return the cached data instead of creating the business object and calling its SelectMethod using reflection. Caching lets you avoid creating the object and calling its data method at the expense of memory on the Web server; this might be a good trade-off. The ObjectDataSource automatically caches data when the EnableCaching property is set to true, and the CacheDuration property is set to the number of seconds that the cache stores data before the cache is discarded. You can also specify a CacheExpirationPolicy property and an optional SqlCacheDependency property.

The following table describes the features of the ObjectDataSource control.

Capability

Requirements

Selecting

Set the SelectMethod property to the name of the business object method that selects data and include any necessary parameters in the SelectParameters collection either programmatically or by using a data-bound control.

Sorting

Set the SortParameterName property to the name of the parameter in the SelectMethod method that carries the sort criteria.

Filtering

Set the FilterExpression property to a filtering expression and optionally add any parameters to the FilterParameters collection to filter the data when the Select method is called. The method specified by the SelectMethod property must return a DataSet, DataView, or DataTable.

Paging

Data source paging is supported, if the SelectMethod method contains parameters for the maximum number of records to retrieve and the index of the first record to retrieve. The names of those parameters must be set in the MaximumRowsParameterName and StartRowIndexParameterName properties, respectively. A data-bound control might be able to perform paging itself, even if the ObjectDataSource control does not support paging directly in the method specified by the SelectMethod property. The requirement for the data-bound control to be able to do this is that the method specified by the SelectMethod property return an object that implements the Icollection interface.

Updating

Set the UpdateMethod property to the name of the business object method that updates data, and include any necessary parameters in the UpdateParameters collection.

Deleting

Set the DeleteMethod property to the name of the business object method or function that deletes data, and include any necessary parameters in the DeleteParameters collection.

Inserting

Set the InsertMethod property to the name of the business object method or function that inserts data, and include any necessary parameters in the InsertParameters collection.

Caching

Set the EnableCaching property to true, and the CacheDuration and CacheExpirationPolicy properties according to the caching behavior you want for your cached data.

As with all data source controls, the ObjectDataSource control is associated with a data source view class. While the ObjectDataSource control is the interface that the page developer uses to work with data, the ObjectDataSourceView class is the interface that data-bound controls work with. Additionally, the ObjectDataSourceView class describes the capabilities of the data source control, and performs the actual work. The ObjectDataSource control has only one associated ObjectDataSourceView, and it is always named DefaultView. While the ObjectDataSourceView object is exposed by the GetView method, many of its properties and methods are wrapped and exposed directly by the ObjectDataSource control. Behind the scenes, the ObjectDataSourceView object performs all data operations, including retrieving, inserting, updating, deleting, filtering, and sorting the data. For more information, see ObjectDataSourceView.

There is no visual rendering of the ObjectDataSource control; it is implemented as a control so that you can create it declaratively and to allow it to participate in state management, optionally. As a result, the ObjectDataSource does not support visual features. such as the EnableTheming or SkinID property.

TopicLocation
How to: Bind to Data in a Templated ControlBuilding ASP .NET Web Applications
How to: Secure Connection Strings When Using Data Source ControlsBuilding ASP .NET Web Applications
How to: Bind to Data in a Templated ControlBuilding ASP .NET Web Applications
How to: Secure Connection Strings When Using Data Source ControlsBuilding ASP .NET Web Applications
Walkthrough: Data Binding Web Pages with a Visual Studio Data ComponentBuilding ASP .NET Web Applications in Visual Studio
How To: Secure Connection Strings when Using Data Source Controls (Visual Studio)Building ASP .NET Web Applications in Visual Studio
How to: Add Repeater Web Server Controls to a Web Forms Page (Visual Studio)Building ASP .NET Web Applications in Visual Studio
Walkthrough: Data Binding to a Custom Business ObjectBuilding ASP .NET Web Applications in Visual Studio
How to: Bind to Data in a Templated Control in Visual StudioBuilding ASP .NET Web Applications in Visual Studio

This section contains two code examples. The first code example demonstrates how a GridView control can display data using an ObjectDataSource object on a Web Forms page. The second code example provides an example middle-tier business object that this and many other ObjectDataSource code examples use.

The following code example demonstrates how a GridView control can display data using an ObjectDataSource control on a Web Forms page. The ObjectDataSource identifies the partially or fully qualified class name of a business object with its TypeName property and a business object method that is called to retrieve data with its SelectMethod property. At run time, the object is created and the method is called using reflection. The GridView control enumerates through the IEnumerable collection that is returned by the SelectMethod and displays the data.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<html>
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

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

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.CS.EmployeeLogic" />

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

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.JSL" Assembly="Samples.AspNet.JSL" %>
<%@ Page language="VJ#" %>
<html>
  <head>
    <title>ObjectDataSource - VJ# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

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

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.JSL.EmployeeLogic" />

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

The following code example provides an example middle-tier business object that this and many other ObjectDataSource code examples use. The code example consists of the following two basic classes:

  • The EmployeeLogic class, which is a stateless class that encapsulates business logic.

  • The NorthwindEmployee class, which is a model class containing only the basic functionality that is required to load and persist data from the data tier.

An additional NorthwindDataException class is provided as a convenience.

This set of example classes works with the Northwind Traders database, which is available with Microsoft SQL Server and Microsoft Access. For a complete working example, you must compile and use these classes with the Web Forms code examples that are provided.

This example is designed to be simple and easy to follow and to demonstrate one of the most common ways a business object interacts with an ObjectDataSource control. It is not a design recommendation. In some examples, additional methods are added to the EmployeeLogic or NorthwindEmployee classes, or modifications are made to this set of classes to demonstrate fundamental concepts.

namespace Samples.AspNet.CS {

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

    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees () {
      ArrayList al = new ArrayList();

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];

      SqlDataSource sds
        = new SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees");

      try {

        IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);

        // Iterate through the Enumeration and create a
        // NorthwindEmployee object for each ID.
        foreach (DataRowView row in IDs) {
          string id = row["EmployeeID"].ToString();
          NorthwindEmployee nwe = new NorthwindEmployee(id);
          // Add the NorthwindEmployee object to the collection.
          al.Add(nwe);
        }
      }
      finally {
        // If anything strange happens, clean up.
        sds.Dispose();
      }

      return al;
    }
    public static NorthwindEmployee GetEmployee(object anID) {
      return new NorthwindEmployee(anID);
    }

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
      bool retval = ne.Save();
      if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
    }

    public static void DeleteEmployee(NorthwindEmployee ne) { }

  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
      title="";
      titleOfCourtesy = "";
      reportsTo = -1;
    }

    public NorthwindEmployee (object anID) {
      this.ID = anID;

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];

		SqlConnection conn = new SqlConnection (cts.ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " FROM Employees " +
                       " WHERE EmployeeID = @empId",
                       conn);
      // Add the employee ID parameter and set its value.
      sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
      SqlDataReader sdr = null;

      try {
        conn.Open();
        sdr = sc.ExecuteReader();

        // This is not a while loop. It only loops once.
        if (sdr != null && sdr.Read()) {
          // The IEnumerable contains DataRowView objects.
          this.firstName        = sdr["FirstName"].ToString();
          this.lastName         = sdr["LastName"].ToString();
          this.title            = sdr["Title"].ToString();
          this.titleOfCourtesy  = sdr["TitleOfCourtesy"].ToString();
          if (! sdr.IsDBNull(4)) {
            this.reportsTo        = sdr.GetInt32(4);
          }
        }
        else {
          throw new NorthwindDataException("Data not loaded for employee id.");
        }
      }
      finally {
        try {
          if (sdr != null) sdr.Close();
          conn.Close();
        }
        catch (SqlException) {
          // Log an event in the Application Event Log.
          throw;
        }
      }
    }

    private object ID;

    private string lastName;
    public string LastName {
      get { return lastName; }
      set { lastName = value; }
    }

    private string firstName;
    public string FirstName {
      get { return firstName; }
      set { firstName = value;  }
    }

    private string title;
    public String Title {
      get { return title; }
      set { title = value; }
    }

    private string titleOfCourtesy;
    public string Courtesy {
      get { return titleOfCourtesy; }
      set { titleOfCourtesy = value; }
    }

    private int    reportsTo;
    public int Supervisor {
      get { return reportsTo; }
      set { reportsTo = value; }
    }

    public bool Save () {
      return true;
    }
  }

  internal class NorthwindDataException: Exception {
    public NorthwindDataException(string msg) : base (msg) { }
  }
}

package  Samples.AspNet.JSL; 

import System.*;
import System.Collections.*;
import System.Collections.Specialized.*;
import System.Configuration.*;
import System.Data.*;
import System.Data.SqlClient.*;
import System.Web.UI.*;
import System.Web.UI.WebControls.*;
   
//
// EmployeeLogic is a stateless business object that encapsulates
// the operations one can perform on a NorthwindEmployee object.
//
public class EmployeeLogic
{
    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees()
        throws NorthwindDataException, SqlException
    {
        ArrayList al = new ArrayList();

        ConnectionStringSettings cts = 
            ConfigurationManager.get_ConnectionStrings().get_Item("NorthwindConnection");

		
        SqlDataSource sds =
            new SqlDataSource(cts.get_ConnectionString(), "SELECT EmployeeID FROM Employees");

        try {
            IEnumerable ids = sds.Select(DataSourceSelectArguments.get_Empty());

            // Iterate through the Enumeration and create a
            // NorthwindEmployee object for each id.
            IEnumerator enumerator = ids.GetEnumerator();
            while (enumerator.MoveNext()) {
                // The IEnumerable contains DataRowView objects.
                DataRowView row = (DataRowView)enumerator.get_Current();
                String id = row.get_Item("EmployeeID").ToString();
                NorthwindEmployee nwe = new NorthwindEmployee(id);
                // Add the NorthwindEmployee object to the collection.
                al.Add(nwe);
            }
        }
        finally {
            // If anything strange happens, clean up.
            sds.Dispose();
        }

        return al;
    } //GetAllEmployees

    public static NorthwindEmployee GetEmployee(Object anId)
        throws NorthwindDataException, SqlException
    {
        return new NorthwindEmployee(anId);
    } //GetEmployee

    public static void UpdateEmployeeInfo(NorthwindEmployee ne)
        throws NorthwindDataException, SqlException
    {
        boolean retval = ne.Save();
        if (!retval) {
            throw new NorthwindDataException("UpdateEmployee failed.");
        }
    } //UpdateEmployeeInfo

    public static void DeleteEmployee(NorthwindEmployee ne)
    {
    } //DeleteEmployee 
} //EmployeeLogic

public class NorthwindEmployee
{
    public NorthwindEmployee()
    {
        id = DBNull.Value;
        lastName = "";
        firstName = "";
        title = "";
        titleOfCourtesy = "";
        reportsTo = -1;
    } //NorthwindEmployee

    public NorthwindEmployee(Object anId)
        throws NorthwindDataException, SqlException
    {
        this.id = anId;

        ConnectionStringSettings cts = 
	    ConfigurationManager.get_ConnectionStrings().get_Item("NorthwindConnection");
	SqlConnection conn = new SqlConnection(cts.get_ConnectionString());
        SqlCommand sc = new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo" +
            " FROM Employees " +
            " WHERE EmployeeID = @empId",
            conn);
        // Add the employee ID parameter and set its value.
        sc.get_Parameters().Add(new SqlParameter("@empId", SqlDbType.Int)).
            set_Value((Int32)Int32.Parse(anId.ToString()));
        SqlDataReader sdr = null;

        try {
            conn.Open();
            sdr = sc.ExecuteReader();
            // This is not a while loop. It only loops once.
            if (sdr != null && sdr.Read()) {
                // The IEnumerable contains DataRowView objects.
                this.firstName = sdr.get_Item("FirstName").ToString();
                this.lastName = sdr.get_Item("LastName").ToString();
                this.title = sdr.get_Item("Title").ToString();
                this.titleOfCourtesy = sdr.get_Item("TitleOfCourtesy").
                    ToString();
                if (!(sdr.IsDBNull(4))) {
                    this.reportsTo = sdr.GetInt32(4);
                }
            }
            else {
                throw new NorthwindDataException("Data not loaded for employee id.");
            }
        }
        finally {
            try {
                if (sdr != null) {
                    sdr.Close();
                }
                conn.Close();
            }
            catch (SqlException exp) {
                // Log an event in the Application Event Log.
                throw exp;
            }
        }
    } //NorthwindEmployee

    private Object id;

    private String lastName;

    /** @property 
     */
    public String get_LastName()
    {
        return lastName;
    } //get_LastName

    /** @property 
     */
    public void set_LastName(String value)
    {
        lastName = value;
    } //set_LastName

    private String firstName;

    /** @property 
     */
    public String get_FirstName()
    {
        return firstName;
    } //get_FirstName

    /** @property 
     */
    public void set_FirstName(String value)
    {
        firstName = value;
    } //set_FirstName

    private String title;

    /** @property 
     */
    public String get_Title()
    {
        return title;
    } //get_Title

    /** @property 
     */
    public void set_Title(String value)
    {
        title = value;
    } //set_Title

    private String titleOfCourtesy;

    /** @property 
     */
    public String get_Courtesy()
    {
        return titleOfCourtesy;
    } //get_Courtesy

    /** @property 
     */
    public void set_Courtesy(String value)
    {
        titleOfCourtesy = value;
    } //set_Courtesy

    private int reportsTo;

    /** @property 
     */
    public int get_Supervisor()
    {
        return reportsTo;
    } //get_Supervisor

    /** @property 
     */
    public void set_Supervisor(int value)
    {
        reportsTo = value;
    } //set_Supervisor

    public boolean Save()
    {
        return true;
    } //Save
} //NorthwindEmployee

public class NorthwindDataException extends System.Exception
{
    public NorthwindDataException(String msg)
    {
         super(msg);
    } //NorthwindDataException
} //NorthwindDataException

System.Object
   System.Web.UI.Control
     System.Web.UI.DataSourceControl
      System.Web.UI.WebControls.ObjectDataSource
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.