Updating, événement

ObjectDataSource.Updating, événement

Remarque : cet événement est nouveau dans le .NET Framework version 2.0.

Se produit avant une opération Update.

Espace de noms : System.Web.UI.WebControls
Assembly : System.Web (dans system.web.dll)

public event ObjectDataSourceMethodEventHandler Updating
/** @event */
public void add_Updating (ObjectDataSourceMethodEventHandler value)

/** @event */
public void remove_Updating (ObjectDataSourceMethodEventHandler value)

JScript prend en charge l'utilisation d'événements mais pas la déclaration de nouveaux événements.

Gérez l'événement Updating pour exécuter une initialisation supplémentaire spécifique à votre application, pour valider les valeurs de paramètres ou pour modifier les valeurs de paramètre avant que le contrôle ObjectDataSource n'exécute l'opération de mise à jour. Les paramètres sont disponibles sous la forme d'une collection IDictionary accessible par la propriété InputParameters, exposée par l'objet ObjectDataSourceMethodEventArgs.

Pour plus d'informations sur la gestion des événements, consultez Consommation d'événements.

Cette section comprend deux exemples de code. Le premier exemple de code illustre comment utiliser un contrôle DropDownList, des contrôles TextBox et plusieurs objets ObjectDataSource pour mettre à jour des données. Le deuxième exemple de code affiche la classe EmployeeLogic qui est utilisée dans le premier exemple de code.

L'exemple de code suivant illustre comment utiliser un contrôle DropDownList, des contrôles TextBox et plusieurs contrôles ObjectDataSource pour mettre à jour des données. DropDownList affiche le nom d'un employé Northwind alors que les contrôles TextBox sont utilisés pour entrer et mettre à jour des informations relatives aux adresses. Étant donné que la collection UpdateParameters contient un ControlParameter qui est lié à la valeur sélectionnée de DropDownList, le bouton qui déclenche l'opération Update est activé uniquement après sélection d'un employé.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<%@ Import namespace="Samples.AspNet.CS" %>
<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) {
    ObjectDataSource2.Update();
}

// Dynamically add parameters to the InputParameters collection.
private void NorthwindEmployeeUpdating(object source, ObjectDataSourceMethodEventArgs e) {

  // The names of the parameters are the same as
  // the variable names for the method that is invoked to
  // perform the Update. The InputParameters collection is
  // an IDictionary collection of name/value pairs,
  // not a ParameterCollection.
  e.InputParameters.Add("anID",       DropDownList1.SelectedValue);
  e.InputParameters.Add("anAddress"  ,AddressBox.Text);
  e.InputParameters.Add("aCity"      ,CityBox.Text);
  e.InputParameters.Add("aPostalCode",PostalCodeBox.Text);
}
</Script>
<html>
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <!-- The DropDownList is bound to the first ObjectDataSource. -->
        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.CS.EmployeeLogic" />

        <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          datasourceid="ObjectDataSource1"
          datatextfield="FullName"
          datavaluefield="EmpID"
          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. -->

        <asp:objectdatasource
          id="ObjectDataSource2"
          runat="server"
          updatemethod="UpdateEmployeeWrapper"
          onupdating="NorthwindEmployeeUpdating"
          typename="Samples.AspNet.CS.EmployeeLogic" />

        <p><asp:textbox
          id="AddressBox"
          runat="server" /></p>

        <p><asp:textbox
          id="CityBox"
          runat="server" /></p>

        <p><asp:textbox
          id="PostalCodeBox"
          runat="server" /></p>

        <asp:button
          id="Button1"
          runat="server"
          text="Update Employee"
          oncommand="Btn_UpdateEmployee" />

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

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.JSL" Assembly="Samples.AspNet.JSL" %>
<%@ Page Language="VJ#" %>
<%@ Import namespace="Samples.AspNet.JSL" %>
<Script runat="server">
    // Add parameters and initialize the user interface
    // only if an employee is selected.
    private void Page_Load(Object sender, System.EventArgs e) throws NorthwindDataException
    {
        // Be sure the text boxes are initialized with
        // data from the currently selected employee.
        NorthwindEmployee selectedEmployee = 
            EmployeeLogic.GetEmployee(DropDownList1.get_SelectedValue());

        if (selectedEmployee != null) {
            AddressBox.set_Text(selectedEmployee.get_Address());
            CityBox.set_Text(selectedEmployee.get_City());
            PostalCodeBox.set_Text(selectedEmployee.get_PostalCode());
            Button1.set_Enabled(true);
        }
        else {
            Button1.set_Enabled(false);
        }
    } //Page_Load

    
    // Press the button to update.
    private void Btn_UpdateEmployee(Object sender, CommandEventArgs e)
    {
        ObjectDataSource2.Update();
    } //Btn_UpdateEmployee


    // Dynamically add parameters to the InputParameters collection.
    private void NorthwindEmployeeUpdating(Object source, 
        ObjectDataSourceMethodEventArgs e)
    {
        // The names of the parameters are the same as
        // the variable names for the method that is invoked to
        // perform the Update. The InputParameters collection is
        // an IDictionary collection of name/value pairs,
        // not a ParameterCollection.
        e.get_InputParameters().Add("anID", DropDownList1.get_SelectedValue());
        e.get_InputParameters().Add("anAddress", AddressBox.get_Text());
        e.get_InputParameters().Add("aCity", CityBox.get_Text());
        e.get_InputParameters().Add("aPostalCode", PostalCodeBox.get_Text());
    } //NorthwindEmployeeUpdating
</Script>
<html>
  <head>
    <title>ObjectDataSource - VJ# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <!-- The DropDownList is bound to the first ObjectDataSource. -->
        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.JSL.EmployeeLogic" />

        <p><asp:dropdownlist
          id="DropDownList1"
          runat="server"
          datasourceid="ObjectDataSource1"
          datatextfield="FullName"
          datavaluefield="EmpID"
          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. -->

        <asp:objectdatasource
          id="ObjectDataSource2"
          runat="server"
          updatemethod="UpdateEmployeeWrapper"
          onupdating="NorthwindEmployeeUpdating"
          typename="Samples.AspNet.JSL.EmployeeLogic" />

        <p><asp:textbox
          id="AddressBox"
          runat="server" /></p>

        <p><asp:textbox
          id="CityBox"
          runat="server" /></p>

        <p><asp:textbox
          id="PostalCodeBox"
          runat="server" /></p>

        <asp:button
          id="Button1"
          runat="server"
          text="Update Employee"
          oncommand="Btn_UpdateEmployee" />

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

L'exemple de code suivant affiche la classe EmployeeLogic qui est utilisée dans l'exemple de code précédent.

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.
          al.Add(nwe);
        }
      }
      finally {
        // If anything strange happens, clean up.
        sds.Dispose();
      }

      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;
      UpdateEmployee(ne);
    }

    // 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",
                       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.address         = sdr["Address"].ToString();
          this.city            = 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();
          conn.Close();
        }
        catch (SqlException) {
          // Log an event in the Application Event Log.
          throw;
        }
      }
    }

    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) { }
  }
}

package Samples.AspNet.JSL; 

import System.*;
import System.Collections.*;
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
    {
        ArrayList al = new ArrayList();
        // Use the SqlDataSource class to wrap the
        // ADO.NET code required to query the database.
        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 idObj = row.get_Item("EmployeeID").ToString();
                NorthwindEmployee nwe = new NorthwindEmployee(idObj);
                // 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
    {
        ArrayList al = (ArrayList)GetAllEmployees();
        IEnumerator enumerator = al.GetEnumerator();
        while (enumerator.MoveNext()) {
            // The IEnumerable contains initialized NorthwindEmployee objects.
            NorthwindEmployee ne = (NorthwindEmployee)enumerator.get_Current();
            if (ne.get_EmpID().Equals(anID.ToString())) {
                return ne;
            }
        }
        return null;
    } //GetEmployee

    public static void UpdateEmployee(NorthwindEmployee ne)
        throws NorthwindDataException
    {
        boolean retVal = ne.Update();
        if (!(retVal)) {
            throw new NorthwindDataException("Employee update failed.");
        }
    } //UpdateEmployee

    // This method is added as a conveniece wrapper on the original
    // implementation.
    public static void UpdateEmployeeWrapper(String anID, String anAddress,
        String aCity, String aPostalCode) throws NorthwindDataException
    {
        NorthwindEmployee ne = new NorthwindEmployee(anID);
        ne.set_Address(anAddress);
        ne.set_City(aCity);
        ne.set_PostalCode(aPostalCode);
        UpdateEmployee(ne);
    } //UpdateEmployeeWrapper
    // And so on...
} //EmployeeLogic

public class NorthwindEmployee
{
    public NorthwindEmployee(Object anID) throws NorthwindDataException
    {
        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,Address,"
            + "City,PostalCode " + " 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(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.address = sdr.get_Item("Address").ToString();
                this.city = sdr.get_Item("City").ToString();
                this.postalCode = sdr.get_Item("PostalCode").ToString();
            }
            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.                  
            }
        }
    } //NorthwindEmployee

    private Object id;

    /** @property 
     */
    public Object get_EmpID()
    {
        return id;
    } //get_EmpID

    private String lastName;

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

    private String firstName;

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

    /** @property 
     */
    public String get_FullName()
    {
        return firstName + " " + lastName;
    } //get_FullName

    private String address;

    /** @property 
     */
    public String get_Address()
    {
        return address;
    } //get_Address

    /** @property 
     */
    public void set_Address(String value)
    {
        address = value;
    } //set_Address

    private String city;

    /** @property
     */
    public String get_City()
    {
        return city;
    } //get_City

    /** @property
     */
    public void set_City(String value)
    {
        city = value;
    } //set_City

    private String postalCode;

    /** @property 
     */
    public String get_PostalCode()
    {
        return postalCode;
    } //get_PostalCode

    /** @property 
     */
    public void set_PostalCode(String value)
    {
        postalCode = value;
    } //set_PostalCode

    public boolean Update()
    {
        // Implement Update logic.
        return true;
    } //Update
} //NorthwindEmployee

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

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

.NET Framework

Prise en charge dans : 2.0

Ajouts de la communauté

AJOUTER
Afficher:
© 2016 Microsoft