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 테이블 로부터 검색 된 데이터를 포함 하는 개체를 serialize 합니다.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 데이터베이스 및 직원 테이블을 나타내는 필요 합니다.The example requires a LINQ to SQL class that represents the Northwind database and Employees table. 자세한 내용은 방법: 만들 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

설명

처리를 Updating 매개 변수의 값을 확인 하거나 전에 매개 변수 값을 변경 하려면 애플리케이션에 관련 된 추가 초기화를 수행 하는 이벤트를 ObjectDataSource 컨트롤이 업데이트 작업을 수행 합니다.Handle 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. 매개 변수를 사용할 수는 IDictionary 액세스 하는 컬렉션을 InputParameters 속성에 의해 노출 되는 ObjectDataSourceMethodEventArgs 개체입니다.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.

적용 대상

추가 정보