This documentation is archived and is not being maintained.

ObjectDataSource.Update Method

Performs an update operation by calling the method that is identified by the UpdateMethod property and any parameters that are in the UpdateParameters collection.

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

public int Update()

Return Value

Type: System.Int32
A value that represents the number of rows updated in the underlying data storage.

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

Before the Update operation is performed, the OnUpdating method is called to raise the Updating event. You can handle the Updating event to examine the values of the parameters and to perform any preprocessing before an Update operation. To perform an update operation, the ObjectDataSourceView object uses reflection to create an instance of the object that is identified by the TypeName property. It then calls the method that is identified by the UpdateMethod property, using any associated UpdateParameters properties. After the Update operation completes, the OnUpdated method is called to raise the Updated event. You can handle the Updated event to examine any return values, output parameters, and exceptions, and to perform any post-processing.

The Update method delegates to the Update method of the ObjectDataSourceView that is associated with the ObjectDataSource control.

For more information about parameter merging, object lifetime, and method resolution, see UpdateMethod.

Security noteSecurity Note

You should validate any parameter value that you receive from the client. The runtime simply substitutes the parameter value into the UpdateMethod property.

Data-Bound Controls

When the ObjectDataSource control is associated with a data-bound control, such as the GridView control, it is not necessary to call the Update method from page code. The Update method is invoked directly by the data-bound control instead.

This section contains two code examples. The first code example demonstrates how to use a DropDownList control, TextBox controls, and several ObjectDataSource objects to update 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 a DropDownList control, TextBox controls, and several ObjectDataSource controls to update data. The DropDownList displays the name of a Northwind employee, while the TextBox controls are used to enter and update address information. Because the UpdateParameters collection contains a ControlParameter object that is bound to the selected value of the DropDownList, the button that raises the Update operation is enabled only after an employee is selected.

Security noteSecurity Note

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<%@ Import namespace="Samples.AspNet.CS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">

// Add parameters and initialize the user interface
// only if an employee is selected.
private void Page_Load(object sender, EventArgs e)
  // Be sure the text boxes are initialized with
  // data from the currently selected employee.
  NorthwindEmployee selectedEmployee = EmployeeLogic.GetEmployee(DropDownList1.SelectedValue);
  if (selectedEmployee != null) {
    AddressBox.Text    = selectedEmployee.Address;
    CityBox.Text       = selectedEmployee.City;
    PostalCodeBox.Text = selectedEmployee.PostalCode;

    Button1.Enabled = true;
  else {
    Button1.Enabled = false;

// Press the button to update.
private void Btn_UpdateEmployee (object sender, CommandEventArgs e) {
<html xmlns="" >
    <title>ObjectDataSource - C# Example</title>
    <form id="Form1" method="post" runat="server">

        <!-- The DropDownList is bound to the first ObjectDataSource. -->
          typename="Samples.AspNet.CS.EmployeeLogic" />

          autopostback="True" /></p>

        <!-- The second ObjectDataSource performs the Update. This
             preserves the state of the DropDownList, which otherwise
             would rebind when the DataSourceChanged event is
             raised as a result of an Update operation. -->

        <!-- Security Note: The ObjectDataSource uses a FormParameter,
             Security Note: which does not perform validation of input from the client.
             Security Note: To validate the value of the FormParameter,
             Security Note: handle the Updating event. -->

            <asp:controlparameter name="anID" controlid="DropDownList1" propertyname="SelectedValue" />
            <asp:formparameter name="anAddress" formfield="AddressBox" />
            <asp:formparameter name="aCity" formfield="CityBox" />
            <asp:formparameter name="aPostalCode" formfield="PostalCodeBox" />

          runat="server" /></p>

          runat="server" /></p>

          runat="server" /></p>

          text="Update Employee"
          oncommand="Btn_UpdateEmployee" />


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 one 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) {
      ArrayList al = GetAllEmployees() as ArrayList;
      IEnumerator enumerator = al.GetEnumerator();
      while (enumerator.MoveNext()) {
        // The IEnumerable contains initialized NorthwindEmployee objects.
        NorthwindEmployee ne = enumerator.Current as NorthwindEmployee;
        if (ne.EmpID.Equals(anID.ToString())) {
          return ne;
      return null;
    public static void UpdateEmployee(NorthwindEmployee ne) {
      bool retval = ne.Update();
      if (! retval) { throw new NorthwindDataException("Employee update failed."); }

    // This method is added as a conveniece wrapper on the original
    // implementation.
    public static void UpdateEmployeeWrapper(string anID,
                                             string anAddress,
                                             string aCity,
                                             string aPostalCode) {
      NorthwindEmployee ne = new NorthwindEmployee(anID);
      ne.Address = anAddress;
      ne.City = aCity;
      ne.PostalCode = aPostalCode;

    // And so on...

  public class NorthwindEmployee {

    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,Address,City,PostalCode " +
                       " 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();
          this.address         = sdr["Address"].ToString();
            = sdr["City"].ToString();
          this.postalCode      = sdr["PostalCode"].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 {
      set { lastName = value; }

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

    public string FullName {
      get { return firstName + " " + lastName; }

    private string address;
    public string Address {
      get { return address; }
      set { address = value;  }

    private string city;
    public string City {
      get { return city; }
      set { city = value;  }

    private string postalCode;
    public string PostalCode {
      get { return postalCode; }
      set { postalCode = value;  }

    public bool Update () {

      // Implement Update logic.

      return true;

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

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

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