This documentation is archived and is not being maintained.

ObjectDataSource.DeleteMethod Property

Gets or sets the name of the method or function that the ObjectDataSource control invokes to delete data.

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

public string DeleteMethod { get; set; }
<asp:ObjectDataSource DeleteMethod="String" />

Property Value

Type: System.String
A string that represents the name of the method or function that the ObjectDataSource uses to delete data. The default is an empty string ("").

The business object is assumed to delete data one record at a time, rather than in a batch.

The DeleteMethod property delegates to the DeleteMethod property of the ObjectDataSourceView object that is associated with the ObjectDataSource control.

Make sure that the parameter names configured for the ObjectDataSource control in the UpdateParameters collection match the column names that are returned by the select method.

Object Lifetime

The method that is identified by the DeleteMethod property can be an instance method or a static (Shared in Visual Basic) method. If it is an instance method, the business object is created and destroyed each time the DeleteMethod property is called. You can handle the ObjectCreated and ObjectCreating events to work with the business object before the DeleteMethod property is called. You can also handle the ObjectDisposing event that is raised after the DeleteMethod property is called. If the business object implements the IDisposable interface, the Dispose method is called before the object is destroyed. If the method is a static (Shared in Visual Basic) method, the business object is never created and you cannot handle the ObjectCreated, ObjectCreating, and ObjectDisposing events.

Parameter Merging

Parameters are added to the DeleteParameters collection from three sources:

  • From the data-bound control, at run time.

  • From the DeleteParameters element, declaratively.

  • From the Deleting method, declaratively.

First, any parameters that are generated from data-bound controls are added to the DeleteParameters collection. For example, if the ObjectDataSource control is bound to a GridView control that has the columns Name and Number, parameters for Name and Number are added to the collection. The exact name of the parameter depends on the OldValuesParameterFormatString property. The data type of these parameters is string. Next, the parameters that are listed in the DeleteParameters element are added. If a parameter in the DeleteParameters element is found with the same name as a parameter that is already in the DeleteParameters collection, the existing parameter is modified to match the parameter that is specified in the DeleteParameters element. Typically, this is used to modify the type of the data in the parameter. Finally, you can programmatically add and remove parameters in the Deleting event, which occurs before the Delete method is run. The method is resolved after the parameters are merged. Method resolution is discussed in the next section.

Method Resolution

When the Delete method is called, the data fields from the data-bound control, the parameters that were created declaratively in the DeleteParameters element, and the parameters that were added in the Deleting event handler are all merged. (For more information, see the preceding section.) The ObjectDataSource object then attempts to find a method to call. First, it looks for one or more methods with the name that is specified in the DeleteMethod property. If no match is found, an InvalidOperationException exception is thrown. If a match is found, it then looks for matching parameter names. For example, suppose the type that is specified by the TypeName property has two methods named DeleteARecord. One DeleteARecord has one parameter, ID, and the other DeleteARecord has two parameters, Name and Number. If the DeleteParameters collection has only one parameter named ID, the DeleteARecord method with just the ID parameter is called. The type of the parameter is not checked in resolving the methods. The order of the parameters does not matter.

If the DataObjectTypeName property is set, the method is resolved in a different way. The ObjectDataSource looks for a method with the name that is specified in the DeleteMethod property that takes one parameter of the type that is specified in the DataObjectTypeName property. In this case, the name of the parameter does not matter.

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 delete data. The second code example shows the EmployeeLogic class 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 delete data. Initially, the GridView control displays a set of all employees, using the method that is specified by the SelectMethod property to retrieve the data from the EmployeeLogic object. Because the AutoGenerateDeleteButton property is set to true, the GridView control automatically displays a Delete button.

If you click the Delete button, the delete operation is performed using the method that is specified by the DeleteMethod property and any parameters that are specified in the DeleteParameters collection. In this code example, some preprocessing and post-processing steps are also performed. The NorthwindEmployeeDeleting delegate is called to handle the Deleting event before the operation is performed, and the NorthwindEmployeeDeleted delegate is called to handle the Deleted event after the operation has completed to perform exception handling. In this example, if a NorthwindDataException is thrown, it is handled by the NorthwindDataException delegate.

<%@ 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 NorthwindEmployeeDeleting(object source, ObjectDataSourceMethodEventArgs e)
  // The GridView passes the ID of the employee 
  // to be deleted. However, the buisiness object, EmployeeLogic, 
  // requires a NorthwindEmployee parameter, named "ne". Create
  // it now and add it to the parameters collection.
  IDictionary paramsFromPage = e.InputParameters;
  if (paramsFromPage["EmpID"] != null) {
    NorthwindEmployee ne
      = new NorthwindEmployee( Int32.Parse(paramsFromPage["EmpID"].ToString()));
    // Remove the old EmpID parameter.
    paramsFromPage.Add("ne", ne);

private void NorthwindEmployeeDeleted(object source, ObjectDataSourceStatusEventArgs e)
  // Handle the Exception if it is a NorthwindDataException 
  if (e.Exception != null)

    // Handle the specific exception type. The ObjectDataSource wraps 
    // any Exceptions in a TargetInvokationException wrapper, so 
    // check the InnerException property for expected Exception types. 
    if (e.Exception.InnerException is NorthwindDataException)
      Label1.Text = e.Exception.InnerException.Message;
      // Because the exception is handled, there is 
      // no reason to throw it.
      e.ExceptionHandled = true;

<html xmlns="" >
    <title>ObjectDataSource - C# Example</title>
    <form id="Form1" method="post" runat="server">

            <asp:boundfield headertext="EmpID" datafield="EmpID" />
            <asp:boundfield headertext="First Name" datafield="FirstName" />
            <asp:boundfield headertext="Last Name" datafield="LastName" />

            <asp:parameter name="EmpID" type="Int32" />

        <asp:label id="Label1" runat="server" />


The following code example shows the EmployeeLogic class that is used in the preceding code 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();

      // Use the SqlDataSource class to wrap the 
      // ADO.NET code required to query the database.
      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) {
      return new NorthwindEmployee(anID);

    public static void DeleteEmployee(NorthwindEmployee ne) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("Employee delete failed."); }
      // Delete the object in memory.
      ne = null;

    public static void DeleteEmployeeByID(int anID) {
        NorthwindEmployee tempEmp = new NorthwindEmployee(anID);

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";

    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 " +
                       " 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();

        // 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();
        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 object EmpID {
      get { return 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;  }
    public bool Delete () {
      if (ID.Equals(DBNull.Value)) {
        // The Employee object is not persisted. 
        return true;
      else {
        // The Employee object is persisted. 
        // Use the SqlDataSource control as a convenient wrapper for 
        // the ADO.NET code needed to delete a record from the database.
        ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
        SqlDataSource sds = new SqlDataSource();

        try {
          sds.ConnectionString = cts.ConnectionString;
          sds.DeleteParameters.Add(new Parameter("empID", TypeCode.Int32, this.ID.ToString()));
          sds.DeleteCommand = "DELETE FROM [Order Details] " + 
              "WHERE OrderID IN (SELECT OrderID FROM Orders WHERE EmployeeID=@empID)";
          sds.DeleteCommand = "DELETE FROM Orders WHERE EmployeeID=@empID";
          sds.DeleteCommand = "DELETE FROM EmployeeTerritories WHERE EmployeeID=@empID";
          sds.DeleteCommand = "DELETE FROM Employees WHERE EmployeeID=@empID";
          return true;
        finally {
          // Clean up resources.

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0





Explained that column names used as update or delete parameters must be in the select method.

Customer feedback.