Export (0) Print
Expand All
Expand Minimize

ObjectDataSourceMethodEventHandler Delegate

Represents the method that will handle the Selecting, Updating, Inserting, or Deleting event of the ObjectDataSource control.

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

public delegate void ObjectDataSourceMethodEventHandler(
	Object sender,
	ObjectDataSourceMethodEventArgs e


Type: System.Object

The source of the event, the ObjectDataSource.

Type: System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs

An ObjectDataSourceMethodEventArgs that contains the event data.

The Selecting, Updating, Inserting, or Deleting event of the ObjectDataSource control allows you to manipulate the parameters that are used to determine the method that is called by the ObjectDataSource control. For more information, see ObjectDataSourceMethodEventArgs.

When you create an ObjectDataSourceMethodEventHandler delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see Consuming Events.

This section contains two code examples. The first code example demonstrates how to use an ObjectDataSource control with a business object and a DetailsView control to insert data. The second code example provides an example middle-tier business object that is used by the first code example.

The following code example demonstrates how to use an ObjectDataSource control with a business object and a DetailsView control to insert data. Initially, the DetailsView displays a new NorthwindEmployee record, along with an automatically generated Insert button. After you enter data into the fields of the DetailsView control, click the Insert button, and the InsertMethod property will identify which method performs the Insert action.

In this example, the UpdateEmployeeInfo method is used to perform an insert; however, it requires a NorthwindEmployee parameter to insert the data. For this reason, the collection of strings that the DetailsView control passes automatically is not sufficient. The NorthwindEmployeeInserting delegate is an ObjectDataSourceMethodEventHandler object that handles the Inserting event and enables you to manipulate the input parameters before the Insert operation proceeds. Because the UpdateEmployeeInfo method requires a NorthwindEmployee object as a parameter, one is created using the collection of strings and is added to the InputParameters collection.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Import namespace="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">
private void NorthwindEmployeeInserting(object source, ObjectDataSourceMethodEventArgs e)
  // The business object expects a custom type. Build it
  // and add it to the parameters collection.

  IDictionary paramsFromPage = e.InputParameters;

  NorthwindEmployee ne = new NorthwindEmployee();

  ne.FirstName  = paramsFromPage["FirstName"].ToString();
  ne.LastName   = paramsFromPage["LastName"].ToString();
  ne.Title      = paramsFromPage["Title"].ToString();
  ne.Courtesy   = paramsFromPage["Courtesy"].ToString();
  ne.Supervisor = Int32.Parse(paramsFromPage["Supervisor"].ToString());

  paramsFromPage.Add("ne", ne);

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


            <asp:parameter name="anID" defaultvalue="-1" />


The following code example provides the example middle-tier business object that the preceding code example uses. The code example consists of the following two basic classes and one additional class:

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

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

  • An additional NorthwindDataException class, which is provided as a convenience.

This set of example classes works with the Northwind Traders database, which is an example database that is available with Microsoft SQL Server and Microsoft Access. For a complete working example, use these classes by placing them in the App_Code directory under the application root or by compiling them into a library and placing the resulting DLL in the Bin directory. The UpdateEmployeeInfo method is not completely implemented, so you will not insert data into the Northwind Traders database when you experiment with this example.

namespace Samples.AspNet.CS {

using System;
using System.Collections;
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 you 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.
        IEnumerator enumerator = IDs.GetEnumerator();
        while (enumerator.MoveNext()) {
          // The IEnumerable contains DataRowView objects.
          DataRowView row = enumerator.Current as DataRowView;
          string id = row["EmployeeID"].ToString();
          NorthwindEmployee nwe = new NorthwindEmployee(id);
          // Add the NorthwindEmployee object to the collection.
      finally {
        // If anything strange happens, clean up.

      return al;

    public static NorthwindEmployee GetEmployee(object anID) {
      if (anID.Equals("-1") ||
          anID.Equals(DBNull.Value) ) {
        return new NorthwindEmployee();
      else {
        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) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("DeleteEmployee failed."); }

    // And so on...

  public class NorthwindEmployee {

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

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

      SqlConnection conn
        = new SqlConnection (ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " FROM Employees " +
                       " WHERE EmployeeID = @empId",
      // 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 {
        sdr = sc.ExecuteReader();

        // Only loop 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();
        catch (SqlException) {
          // Log an event in the Application Event Log. 

    private object ID;
    public string EmpID {
      get { return ID.ToString();  }

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

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

    public string FullName {
      get { return FirstName + " " + LastName; }

    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 () {
      // Implement persistence logic. 
      return true;

    public bool Delete () {
      // Implement delete logic. 
      return true;

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

© 2014 Microsoft