ObjectDataSourceMethodEventArgs 클래스

정의

Inserting 컨트롤의 Updating, DeletingObjectDataSource 이벤트에 대한 데이터를 제공합니다.

public ref class ObjectDataSourceMethodEventArgs : System::ComponentModel::CancelEventArgs
public class ObjectDataSourceMethodEventArgs : System.ComponentModel.CancelEventArgs
type ObjectDataSourceMethodEventArgs = class
    inherit CancelEventArgs
Public Class ObjectDataSourceMethodEventArgs
Inherits CancelEventArgs
상속
ObjectDataSourceMethodEventArgs
파생

예제

이 섹션에는 두 코드 예제가 있습니다. 첫 번째 코드 예제에 사용 하는 방법을 보여 줍니다.는 ObjectDataSource 비즈니스 개체를 사용 하 여 컨트롤 및 DetailsView 데이터 삽입을 제어 합니다. 두 번째 코드 예제에서는 첫 번째 코드 예제에서 사용 되는 예제에서는 중간 계층 비즈니스 개체를 제공 합니다.

다음 코드 예제에 사용 하는 방법을 보여 줍니다.는 ObjectDataSource 비즈니스 개체를 사용 하 여 컨트롤 및 DetailsView 데이터 삽입을 제어 합니다. 합니다 DetailsView 처음에 새 표시 NorthwindEmployee 함께 자동으로 생성 된 레코드 삽입 단추입니다. 데이터의 필드에 입력 한 후는 DetailsView 컨트롤을 클릭 합니다 삽입 단추 및 InsertMethod 속성에서 수행 하는 메서드를 식별 합니다를 Insert 작업.

이 예제에서는 합니다 UpdateEmployeeInfo 그러나; 메서드는 삽입을 수행 하는 NorthwindEmployee 데이터를 삽입 하려면 매개 변수입니다. 따라서 컬렉션 하는 문자열을 DetailsView 컨트롤 전달 자동으로 충분 하지 않습니다. NorthwindEmployeeInserting 대리자가는 ObjectDataSourceMethodEventHandler 처리 하는 개체를 Inserting 이벤트 이전 입력된 매개 변수를 조작할 수 있습니다는 Insert 작업 진행 합니다. 때문에 합니다 UpdateEmployeeInfo 메서드를 사용 하려면를 NorthwindEmployee 개체를 매개 변수로 하나 문자열의 컬렉션을 사용 하 여 추가할를 InputParameters 컬렉션입니다.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Import namespace="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void NorthwindEmployeeInserting(object source, ObjectDataSourceMethodEventArgs e)
{
  // The business object expects a custom type. Build it
  // and add it to the parameters collection.
  
  IDictionary paramsFromPage = e.InputParameters;

  NorthwindEmployee ne = new NorthwindEmployee();

  ne.FirstName  = paramsFromPage["FirstName"].ToString();
  ne.LastName   = paramsFromPage["LastName"].ToString();
  ne.Title      = paramsFromPage["Title"].ToString();
  ne.Courtesy   = paramsFromPage["Courtesy"].ToString();
  ne.Supervisor = Int32.Parse(paramsFromPage["Supervisor"].ToString());

  paramsFromPage.Clear();
  paramsFromPage.Add("ne", ne);
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.CS.EmployeeLogic"
          >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </asp:objectdatasource>

    </form>
  </body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Import namespace="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub NorthwindEmployeeInserting(source As Object, e As ObjectDataSourceMethodEventArgs)

  ' The GridView control passes an array of strings in the parameters
  ' collection because that is the type it knows how to work with.
  ' However, the business object expects a custom type. Build it
  ' and add it to the parameters collection.
  Dim paramsFromPage As IDictionary = e.InputParameters

  Dim ne As New NorthwindEmployee()
  ne.FirstName  = paramsFromPage("FirstName").ToString()
  ne.LastName   = paramsFromPage("LastName").ToString()
  ne.Title      = paramsFromPage("Title").ToString()
  ne.Courtesy   = paramsFromPage("Courtesy").ToString()
  ne.Supervisor = Int32.Parse(paramsFromPage("Supervisor").ToString())
  
  paramsFromPage.Clear()
  paramsFromPage.Add("ne", ne)
End Sub ' NorthwindEmployeeInserting

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - VB Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.VB.EmployeeLogic" >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </asp:objectdatasource>

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

다음 코드 예제에서는 앞의 코드 예제를 사용 하는 예제에서는 중간 계층 비즈니스 개체를 제공 합니다. 다음은 코드 예제에 정의 된 두 개의 주요 클래스를 설명 합니다.

  • EmployeeLogic 비즈니스 논리를 캡슐화 하는 상태 비저장 클래스 클래스.

  • NorthwindEmployee 클래스를 로드 하 고 데이터 계층에서 데이터를 유지 하는 데 필요한 기본적인 기능만 포함 하는 모델 클래스입니다.

또한는 NorthwindDataException 클래스는 편의 위해 제공 됩니다.

이 예제에서는 클래스이 집합을 Microsoft SQL Server 및 Microsoft Access를 사용 하 여 사용할 수 있는 예제 데이터베이스는 Northwind Traders 데이터베이스를 사용 합니다. 전체 작업 예제를 컴파일하고 결과 DLL이 Bin 디렉터리에 배치 하거나 애플리케이션 루트의 App_Code 디렉터리에 배치 하 여 이러한 클래스를 사용 합니다. UpdateEmployeeInfo 메서드 구현 되지 않은 완전히 하지 삽입할 데이터 Northwind Traders 데이터베이스이 예제를 테스트할 때 있도록 합니다.

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 you can perform on a NorthwindEmployee object.
  //
  public class EmployeeLogic {

    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees () {
      ArrayList al = new ArrayList();

      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) {
      if (anID.Equals("-1") ||
          anID.Equals(DBNull.Value) ) {
        return new NorthwindEmployee();
      }
      else {
        return new NorthwindEmployee(anID);
      }
    }

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
      bool retval = ne.Save();
      if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
    }

    public static void DeleteEmployee(NorthwindEmployee ne) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("DeleteEmployee failed."); }
    }

    // And so on...
  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
      title="";
      titleOfCourtesy = "";
      reportsTo = -1;
    }

    public NorthwindEmployee (object anID) {
      this.ID = anID;

      SqlConnection conn
        = new SqlConnection (ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " 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();

        // Only loop once.
        if (sdr != null && sdr.Read()) {
          // The IEnumerable contains DataRowView objects.
          this.firstName        = sdr["FirstName"].ToString();
          this.lastName         = sdr["LastName"].ToString();
          this.title            = sdr["Title"].ToString();
          this.titleOfCourtesy  = sdr["TitleOfCourtesy"].ToString();
          if (! sdr.IsDBNull(4)) {
            this.reportsTo        = sdr.GetInt32(4);
          }
        }
        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 string EmpID {
      get { return ID.ToString();  }
    }

    private string lastName;
    public string LastName {
      get { return lastName; }
      set { lastName = value; }
    }

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

    public string FullName {
      get { return FirstName + " " + LastName; }
    }

    private string title;
    public String Title {
      get { return title; }
      set { title = value; }
    }

    private string titleOfCourtesy;
    public string Courtesy {
      get { return titleOfCourtesy; }
      set { titleOfCourtesy = value; }
    }

    private int    reportsTo;
    public int Supervisor {
      get { return reportsTo; }
      set { reportsTo = value; }
    }

    public bool Save () {
      // Implement persistence logic.
      return true;
    }

    public bool Delete () {
      // Implement delete 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 you 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()

      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
      If anID.Equals("-1") OrElse anID.Equals(DBNull.Value) Then
         Return New NorthwindEmployee()
      Else
         Return New NorthwindEmployee(anID)
      End If
   End Function 'GetEmployee


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

   Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Delete()
      If Not retval Then
         Throw New NorthwindDataException("DeleteEmployee failed.")
      End If
   End Sub

   ' And so on...

End Class


Public Class NorthwindEmployee


   Public Sub New()
      ID = DBNull.Value
      lastName = ""
      firstName = ""
      title = ""
      titleOfCourtesy = ""
      reportsTo = - 1
   End Sub


   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,Title,TitleOfCourtesy,ReportsTo " & _
                               " 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()

         ' Only loop 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.aTitle = sdr("Title").ToString()
            Me.titleOfCourtesy = sdr("TitleOfCourtesy").ToString()
            If Not sdr.IsDBNull(4) Then
               Me.reportsTo = sdr.GetInt32(4)
            End If
         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 String
      Get
         Return ID.ToString()
      End Get
   End Property

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

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

   Public ReadOnly Property FullName() As String
      Get
         Return FirstName & " " & LastName
      End Get
   End Property

   Private aTitle As String
   Public Property Title() As String
      Get
         Return aTitle
      End Get
      Set
         aTitle = value
      End Set
   End Property

   Private titleOfCourtesy As String
   Public Property Courtesy() As String
      Get
         Return titleOfCourtesy
      End Get
      Set
         titleOfCourtesy = value
      End Set
   End Property

   Private reportsTo As Integer
   Public Property Supervisor() As Integer
      Get
         Return reportsTo
      End Get
      Set
         reportsTo = value
      End Set
   End Property

   Public Function Save() As Boolean

      ' Implement persistence logic.
      Return True

   End Function 'Save


   Public Function Delete() As Boolean

     ' Implement delete logic.
     Return True

   End Function 'Delete
End Class


Friend Class NorthwindDataException
   Inherits Exception

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

End Namespace

설명

ObjectDataSourceMethodEventArgs 클래스는를 OnSelecting, OnUpdating, OnInserting, 및 OnDeleting 에 전달 되는 입력 매개 변수에 대 한 액세스를 제공 하는 메서드는 Select, Update, Delete, 및 Insert의 메서드는 ObjectDataSource 제어 합니다. 이러한 매개 변수를 사용 하 여 액세스를 InputParameters 속성입니다. 처리 하는 대리자를 추가 하 여는 Selecting, Updating, Inserting, 또는 Deleting 이벤트를 검토 하 고 매개 변수의 값을 조작 하 고 필요한 모든 추가 전처리를 수행할 수 있습니다. 이 사전 매개 변수 변경 작업에는 메서드 오버 로드 라고 적용 됩니다. 경우는 DataObjectTypeName 속성의는 ObjectDataSource 컨트롤이 설정 된이 사전의 항목에 대 한 데이터 개체 속성을 수정할 수 있습니다, 추가 하거나 매개 변수를 제거할 수 없습니다. 자세한 내용은 Delete를 참조하세요.

ObjectDataSource 컨트롤 수명 주기에서 다양 한 시간에 기본 비즈니스 개체를 사용 하 여 작업을 처리할 수 있는 많은 이벤트를 노출 합니다. 다음 표에서 이벤트를 나열 하 고 연결 된 EventArgs 클래스 및 이벤트 처리기 대리자입니다.

이벤트 EventArgs 클래스 EventHandler 대리자
ObjectCreating.

비즈니스 개체의 인스턴스가 만들어질 직전에 발생 합니다.
ObjectDataSourceEventArgs ObjectDataSourceObjectEventHandler
ObjectCreated.

비즈니스 개체의 인스턴스를 만든 직후에 발생 합니다.
ObjectDataSourceEventArgs ObjectDataSourceObjectEventHandler
Selecting.

데이터를 검색 하기 전에 발생 합니다.
ObjectDataSourceSelectingEventArgs ObjectDataSourceSelectingEventHandler
Inserting, UpdatingDeleting.

삽입, 업데이트 또는 삭제 작업을 수행 하기 전에 발생 합니다.
ObjectDataSourceMethodEventArgs ObjectDataSourceMethodEventHandler
Selected.

데이터를 검색 한 후에 발생 합니다.
ObjectDataSourceStatusEventArgs ObjectDataSourceStatusEventHandler
Inserted, UpdatedDeleted.

삽입, 업데이트 또는 삭제 작업이 완료 되 면 발생 합니다.
ObjectDataSourceStatusEventArgs ObjectDataSourceStatusEventHandler
ObjectDisposing.

비즈니스 개체를 제거 하기 전에 발생 합니다.
ObjectDataSourceDisposingEventArgs ObjectDataSourceDisposingEventHandler

생성자

ObjectDataSourceMethodEventArgs(IOrderedDictionary)

지정된 입력 매개 변수 컬렉션을 사용하여 ObjectDataSourceMethodEventArgs 클래스의 새 인스턴스를 초기화합니다.

속성

Cancel

이벤트를 취소해야 할지 여부를 나타내는 값을 가져오거나 설정합니다.

(다음에서 상속됨 CancelEventArgs)
InputParameters

비즈니스 개체 메서드 매개 변수와 해당 값이 들어 있는 컬렉션을 가져옵니다.

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보