Freigeben über


ObjectDataSource.Update Methode

Definition

Führt einen Aktualisierungsvorgang durch Aufrufen der von der UpdateMethod-Eigenschaft angegebenen Methode mit sämtlichen Parametern in der UpdateParameters-Auflistung aus.

public:
 int Update();
public int Update ();
member this.Update : unit -> int
Public Function Update () As Integer

Gibt zurück

Ein Wert, der die Anzahl der im zugrunde liegenden Datenspeicher aktualisierten Zeilen darstellt.

Beispiele

Dieser Abschnitt enthält zwei Codebeispiele. Im ersten Codebeispiel wird veranschaulicht, wie Sie ein DropDownList Steuerelement, TextBox Steuerelemente und mehrere ObjectDataSource Objekte zum Aktualisieren von Daten verwenden. Das zweite Codebeispiel zeigt die EmployeeLogic Klasse, die im ersten Codebeispiel verwendet wird.

Im folgenden Codebeispiel wird veranschaulicht, wie Sie ein DropDownList Steuerelement, TextBox Steuerelemente und mehrere ObjectDataSource Steuerelemente verwenden, um Daten zu aktualisieren. Zeigt DropDownList den Namen eines Northwind-Mitarbeiters an, während die TextBox Steuerelemente zum Eingeben und Aktualisieren von Adressinformationen verwendet werden. Da die UpdateParameters Auflistung ein ControlParameter Objekt enthält, das an den ausgewählten Wert von DropDownListgebunden ist, wird die Schaltfläche, die den Update Vorgang auslöst, erst aktiviert, nachdem ein Mitarbeiter ausgewählt wurde.

Wichtig

Dieses Beispiel umfasst ein Textfeld, das Benutzereingaben akzeptiert, die ein potenzielles Sicherheitsrisiko darstellen. Standardmäßig stellen ASP.NET-Webseiten sicher, dass Benutzereingaben keine Skript- oder HTML-Elemente enthalten. Weitere Informationen finden Sie unter Übersicht über Skriptangriffe.

<%@ 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"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <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. -->

        <!-- 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:objectdatasource
          id="ObjectDataSource2"
          runat="server"
          updatemethod="UpdateEmployeeWrapper"
          typename="Samples.AspNet.CS.EmployeeLogic">
          <updateparameters>
            <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" />
          </updateparameters>
        </asp:objectdatasource>

        <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.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<%@ Import namespace="Samples.AspNet.VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

' Add parameters and initialize the user interface
' only if an employee is selected.
Private Sub Page_Load(sender As Object, e As EventArgs)

  ' Be sure the text boxes are initialized with
  ' data from the currently selected employee.
  Dim selectedEmployee As NorthwindEmployee
  selectedEmployee = EmployeeLogic.GetEmployee(DropDownList1.SelectedValue)

  If Not selectedEmployee Is Nothing Then
    AddressBox.Text    = selectedEmployee.Address
    CityBox.Text       = selectedEmployee.City
    PostalCodeBox.Text = selectedEmployee.PostalCode

    Button1.Enabled = True
  Else
    Button1.Enabled = False
  End If
End Sub ' Page_Load

' Press the button to update.
Private Sub Btn_UpdateEmployee (sender As Object, e As CommandEventArgs )
  ObjectDataSource2.Update()
End Sub ' Btn_UpdateEmployee

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - VB 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.VB.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. -->

        <!-- 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:objectdatasource
          id="ObjectDataSource2"
          runat="server"
          updatemethod="UpdateEmployeeWrapper"
          typename="Samples.AspNet.VB.EmployeeLogic">
          <updateparameters>
            <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" />
          </updateparameters>
        </asp:objectdatasource>

        <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>

Das folgende Codebeispiel zeigt die EmployeeLogic Klasse, die im vorherigen Codebeispiel verwendet wird.

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) { }
  }
}
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.VB
'
' 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 Shared Function GetAllEmployees() As ICollection
      Dim al As New ArrayList()

      ' Use the SqlDataSource class to wrap the
      ' ADO.NET code required to query the database.
      Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
      Dim sds As New SqlDataSource(cts.ConnectionString, _
                                  "SELECT EmployeeID FROM Employees")
      Try
         Dim IDs As IEnumerable = sds.Select(DataSourceSelectArguments.Empty)

         ' Iterate through the Enumeration and create a
         ' NorthwindEmployee object for each ID.
         Dim enumerator As IEnumerator = IDs.GetEnumerator()
         While enumerator.MoveNext()
            ' The IEnumerable contains DataRowView objects.
            Dim row As DataRowView = CType(enumerator.Current,DataRowView)
            Dim id As String = row("EmployeeID").ToString()
            Dim nwe As New NorthwindEmployee(id)
            ' Add the NorthwindEmployee object to the collection.
            al.Add(nwe)
         End While
      Finally
         ' If anything strange happens, clean up.
         sds.Dispose()
      End Try

      Return al
   End Function 'GetAllEmployees


   Public Shared Function GetEmployee(anID As Object) As NorthwindEmployee
      Dim al As ArrayList = CType(GetAllEmployees(), ArrayList)
      Dim enumerator As IEnumerator = al.GetEnumerator()
      While enumerator.MoveNext()
         ' The IEnumerable contains initialized NorthwindEmployee objects.
         Dim ne As NorthwindEmployee = CType(enumerator.Current,NorthwindEmployee)
         If ne.EmpID.Equals(anID.ToString()) Then
            Return ne
         End If
      End While
      Return Nothing
   End Function 'GetEmployee

   Public Shared Sub UpdateEmployee(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Update()
      If Not retval Then
         Throw New NorthwindDataException("Employee update failed.")
      End If
   End Sub

   ' This method is added as a conveniece wrapper on the original
   ' implementation.
   Public Shared Sub UpdateEmployeeWrapper(anID As String, _
                                           anAddress As String, _
                                           aCity As String, _
                                           aPostalCode As String)
      Dim ne As New NorthwindEmployee(anID)
      ne.Address = anAddress
      ne.City = aCity
      ne.PostalCode = aPostalCode
      UpdateEmployee(ne)
   End Sub
   ' And so on...

End Class

Public Class NorthwindEmployee

   Public Sub New(anID As Object)
      Me.ID = anID
      Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
      Dim conn As New SqlConnection(cts.ConnectionString)
      Dim sc As 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())
      Dim sdr As SqlDataReader = Nothing

      Try
         conn.Open()
         sdr = sc.ExecuteReader()

         ' This is not a while loop. It only loops once.
         If Not (sdr Is Nothing) AndAlso sdr.Read() Then
            ' The IEnumerable contains DataRowView objects.
            Me.aFirstName = sdr("FirstName").ToString()
            Me.aLastName = sdr("LastName").ToString()
            Me.aAddress = sdr("Address").ToString()
            Me.aCity = sdr("City").ToString()
            Me.aPostalCode = sdr("PostalCode").ToString()
         Else
            Throw New NorthwindDataException("Data not loaded for employee id.")
         End If
      Finally
         Try
            If Not (sdr Is Nothing) Then
               sdr.Close()
            End If
            conn.Close()
         Catch se As SqlException
            ' Log an event in the Application Event Log.
            Throw
         End Try
      End Try
   End Sub

   Private ID As Object
   Public ReadOnly Property EmpID() As Object
      Get
         Return ID
      End Get
   End Property

   Private aLastName As String
   Public WriteOnly Property LastName() As String
      Set
         aLastName = value
      End Set
   End Property

   Private aFirstName As String
   Public WriteOnly Property FirstName() As String
      Set
         aFirstName = value
      End Set
   End Property

   Public ReadOnly Property FullName() As String
      Get
         Return aFirstName & " " & aLastName
      End Get
   End Property

   Private aAddress As String
   Public Property Address() As String
      Get
         Return aAddress
      End Get
      Set
         aAddress = value
      End Set
   End Property

   Private aCity As String
   Public Property City() As String
      Get
         Return aCity
      End Get
      Set
         aCity = value
      End Set
   End Property

   Private aPostalCode As String
   Public Property PostalCode() As String
      Get
         Return aPostalCode
      End Get
      Set
         aPostalCode = value
      End Set
   End Property

   Public Function Update() As Boolean

      ' Implement Update logic.
      Return True

   End Function 'Update

End Class

Friend Class NorthwindDataException
   Inherits Exception

   Public Sub New(msg As String)
      MyBase.New(msg)
   End Sub

End Class
End Namespace

Hinweise

Es wird davon ausgegangen, dass das Geschäftsobjekt daten jeweils einen Datensatz aktualisiert und nicht in einem Batch.

Bevor der Update Vorgang ausgeführt wird, wird die OnUpdating -Methode aufgerufen, um das Ereignis auszulösen Updating . Sie können das Updating Ereignis behandeln, um die Werte der Parameter zu untersuchen und vor einem Update Vorgang eine Vorverarbeitung durchzuführen. Zum Ausführen eines Aktualisierungsvorgangs verwendet das Objekt Reflektion ObjectDataSourceView , um eine Instanz des Objekts zu erstellen, das durch die TypeName -Eigenschaft identifiziert wird. Anschließend wird die Methode aufgerufen, die von der UpdateMethod -Eigenschaft mit allen zugeordneten UpdateParameters Eigenschaften identifiziert wird. Nach Abschluss des Update Vorgangs wird die OnUpdated -Methode aufgerufen, um das Ereignis auszulösen Updated . Sie können das Updated Ereignis behandeln, um alle Rückgabewerte, Ausgabeparameter und Ausnahmen zu untersuchen und eine Nachverarbeitung durchzuführen.

Die Update -Methode delegiert an die Update -Methode der, die ObjectDataSourceView dem ObjectDataSource Steuerelement zugeordnet ist.

Weitere Informationen zum Zusammenführen von Parametern, zur Objektlebensdauer und zur Methodenauflösung finden Sie unter UpdateMethod.

Wichtig

Sie sollten jeden Parameterwert überprüfen, den Sie vom Client erhalten. Die Runtime ersetzt einfach den Parameterwert in der UpdateMethod -Eigenschaft.

Datengebundene Steuerelemente

Wenn das ObjectDataSource Steuerelement einem datengebundenen Steuerelement wie dem GridView -Steuerelement zugeordnet ist, ist es nicht erforderlich, die -Methode über Seitencode Update aufzurufen. Die Update -Methode wird stattdessen direkt vom datengebundenen Steuerelement aufgerufen.

Gilt für:

Weitere Informationen