ObjectDataSource.Updating ObjectDataSource.Updating ObjectDataSource.Updating ObjectDataSource.Updating Event

定义

Update() 操作前发生。Occurs before an Update() operation.

public:
 event System::Web::UI::WebControls::ObjectDataSourceMethodEventHandler ^ Updating;
public event System.Web.UI.WebControls.ObjectDataSourceMethodEventHandler Updating;
member this.Updating : System.Web.UI.WebControls.ObjectDataSourceMethodEventHandler 
Public Custom Event Updating As ObjectDataSourceMethodEventHandler 

示例

以下三个示例演示了一个网页、一个代码隐藏页类和一个数据访问类, 使用户能够在 Northwind 数据库中检索和更新 Employees 表中的记录。The following three examples show a Web page, a code-behind page class, and a data-access class that enable a user to retrieve and update records in the Employees table in the Northwind database.

第一个示例显示一个网页, 其中包含两ObjectDataSource个控件DropDownList : 控件和一个DetailsView控件。The first example shows a Web page that contains two ObjectDataSource controls, a DropDownList control, and a DetailsView control. 第一个ObjectDataSource控件DropDownList和控件用于检索和显示数据库中的雇员姓名。The first ObjectDataSource control and the DropDownList control are used to retrieve and display employee names from the database. 第二ObjectDataSource个控件DetailsView和控件用于从用户选择的员工记录中检索、显示和修改数据。The second ObjectDataSource control and the DetailsView control are used to retrieve, display, and modify the data from the employee record that is selected by the user.

<form id="Form1" method="post" runat="server">

    <asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />

    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>

    <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      UpdateMethod="UpdateEmployeeAddress"
      OnUpdating="EmployeeUpdating"
      OnSelected="EmployeeSelected"
      TypeName="Samples.AspNet.CS.EmployeeLogic" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false"
        AutoGenerateEditButton="true">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
   
</form>
<form id="form1" runat="server">

    <asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />

    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>

    <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      UpdateMethod="UpdateEmployeeAddress"
      OnUpdating="EmployeeUpdating"
      OnSelected="EmployeeSelected"
      TypeName="Samples.AspNet.CS.EmployeeLogic" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false"
        AutoGenerateEditButton="true">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
   
</form>

第二个示例显示了SelectedUpdating事件的处理程序。The second example shows handlers for the Selected and Updating events. Selected事件处理程序将序列化包含从 Employee 表中检索到的数据的对象。The Selected event handler serializes the object that contains data that was retrieved from the Employee table. 序列化的对象存储在视图状态中。The serialized object is stored in view state. Updating事件处理程序在视图状态中对对象进行反序列化, 其中包含要更新的数据记录的原始数据。The Updating event handler deserializes the object in view state that contains the original data for the data record that is being updated. 包含原始数据的对象将作为参数传递给 Update 方法。The object that contains the original data is passed as a parameter to the Update method. 必须将原始数据传递到数据库, 以便可以使用它来检查数据是否已被其他进程修改。The original data must be passed to the database so that it can be used to check whether the data has been modified by another process.

public void EmployeeUpdating(object source, ObjectDataSourceMethodEventArgs e)
{
    DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));

    String xmlData = ViewState["OriginalEmployee"].ToString();
    XmlReader reader = XmlReader.Create(new StringReader(xmlData));
    Employee originalEmployee = (Employee)dcs.ReadObject(reader);
    reader.Close();

    e.InputParameters.Add("originalEmployee", originalEmployee);
}

public void EmployeeSelected(object source, ObjectDataSourceStatusEventArgs e)
{
    if (e.ReturnValue != null)
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);
        dcs.WriteObject(writer, e.ReturnValue);
        writer.Close();

        ViewState["OriginalEmployee"] = sb.ToString();
    }
}
Public Sub EmployeeUpdating(ByVal source As Object, ByVal e As ObjectDataSourceMethodEventArgs)
    Dim dcs As New DataContractSerializer(GetType(Employee))
    Dim xmlData As String
    Dim reader As XmlReader
    Dim originalEmployee As Employee

    xmlData = ViewState("OriginalEmployee").ToString()
    reader = XmlReader.Create(New StringReader(xmlData))
    originalEmployee = CType(dcs.ReadObject(reader), Employee)
    reader.Close()

    e.InputParameters.Add("originalEmployee", originalEmployee)
End Sub

Public Sub EmployeeSelected(ByVal source As Object, ByVal e As ObjectDataSourceStatusEventArgs)
    If e.ReturnValue IsNot Nothing Then
        Dim dcs As New DataContractSerializer(GetType(Employee))
        Dim sb As New StringBuilder()
        Dim writer As XmlWriter
        writer = XmlWriter.Create(sb)
        dcs.WriteObject(writer, e.ReturnValue)
        writer.Close()

        ViewState("OriginalEmployee") = sb.ToString()
    End If
End Sub

第三个示例显示与 Northwind 数据库交互的数据访问类。The third example shows the data access class that interacts with the Northwind database. 类使用 LINQ 来查询和更新 Employees 表。The class uses LINQ to query and update the Employees table. 该示例需要一个 LINQ to SQL 类, 该类表示 Northwind 数据库和 Employees 表。The example requires a LINQ to SQL class that represents the Northwind database and Employees table. 有关详细信息,请参阅如何:在 Web 项目中创建 LINQ to SQL 类。For more information, see How to: Create LINQ to SQL Classes in a Web Project.

public class EmployeeLogic
{
    public static Array GetFullNamesAndIDs()
    {
        NorthwindDataContext ndc = new NorthwindDataContext();

        var employeeQuery =
            from e in ndc.Employees
            orderby e.LastName
            select new { FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID };

        return employeeQuery.ToArray();
    }

    public static Employee GetEmployee(int empID)
    {
        if (empID < 0)
        {
            return null;
        }
        else
        {
            NorthwindDataContext ndc = new NorthwindDataContext();
            var employeeQuery =
                from e in ndc.Employees
                where e.EmployeeID == empID
                select e;

            return employeeQuery.Single();
        }
    }
 
    public static void UpdateEmployeeAddress(Employee originalEmployee, string address, string city, string postalcode)
    {
        NorthwindDataContext ndc = new NorthwindDataContext();
        ndc.Employees.Attach(originalEmployee, false);
        originalEmployee.Address = address;
        originalEmployee.City = city;
        originalEmployee.PostalCode = postalcode;
        ndc.SubmitChanges();
    }
}
Public Class EmployeeLogic
    Public Shared Function GetFullNamesAndIDs() As Array
        Dim ndc As New NorthwindDataContext()

        Dim employeeQuery = _
            From e In ndc.Employees _
            Order By e.LastName _
            Select FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID

        Return employeeQuery.ToArray()
    End Function

    Public Shared Function GetEmployee(ByVal empID As Integer) As Employee

        If (empID < 0) Then
            Return Nothing
        Else
            Dim ndc As New NorthwindDataContext()
            Dim employeeQuery = _
                From e In ndc.Employees _
                Where e.EmployeeID = empID _
                Select e

            Return employeeQuery.Single()
        End If
    End Function

    Public Shared Sub UpdateEmployeeAddress(ByVal originalEmployee As Employee, ByVal address As String, ByVal city As String, ByVal postalcode As String)

        Dim ndc As New NorthwindDataContext()
        ndc.Employees.Attach(originalEmployee, False)
        originalEmployee.Address = address
        originalEmployee.City = city
        originalEmployee.PostalCode = postalcode
        ndc.SubmitChanges()
    End Sub
End Class

注解

处理事件以执行特定于您的应用程序的其他初始化, 验证参数的值, 或者在ObjectDataSource控件执行更新操作之前更改参数值。 UpdatingHandle the Updating event to perform additional initialization that is specific to your application, to validate the values of parameters, or to change the parameter values before the ObjectDataSource control performs the update operation. 参数可用作IDictionaryObjectDataSourceMethodEventArgs对象公开的InputParameters属性所访问的集合。The parameters are available as an IDictionary collection that is accessed by the InputParameters property, which is exposed by the ObjectDataSourceMethodEventArgs object.

有关如何处理事件的详细信息, 请参阅处理和引发事件For more information about how to handle events, see Handling and Raising Events.

适用于

另请参阅