ObjectDataSource.DeleteMethod 속성

정의

ObjectDataSource 컨트롤에서 데이터 삭제를 위해 호출하는 메서드나 함수의 이름을 가져오거나 설정합니다.

public:
 property System::String ^ DeleteMethod { System::String ^ get(); void set(System::String ^ value); };
public string DeleteMethod { get; set; }
member this.DeleteMethod : string with get, set
Public Property DeleteMethod As String

속성 값

ObjectDataSource에서 데이터를 삭제할 때 사용하는 메서드나 함수의 이름을 나타내는 문자열입니다. 기본값은 빈 문자열("")입니다.

예제

이 섹션에는 두 코드 예제가 있습니다. 첫 번째 코드 예제에 사용 하는 방법을 보여 줍니다.는 ObjectDataSource 비즈니스 개체를 사용 하 여 개체 및 GridView 컨트롤 데이터를 삭제 합니다. 두 번째 코드 예에서는 EmployeeLogic 첫 번째 코드 예제에 사용 되는 클래스입니다.

다음 코드 예제에 사용 하는 방법을 보여 줍니다.는 ObjectDataSource 비즈니스 개체를 사용 하 여 컨트롤 및 GridView 컨트롤 데이터를 삭제 합니다. 처음에 GridView 컨트롤 집합에 지정 된 메서드를 사용 하 여 모든 직원을 표시 합니다 SelectMethod 속성에서 데이터를 검색 하는 EmployeeLogic 개체. 때문에 AutoGenerateDeleteButton 속성이 trueGridView 컨트롤이 자동으로 표시를 삭제 단추입니다.

클릭할 경우는 삭제 단추를 삭제 작업에 지정 된 메서드를 사용 하 여 수행 됩니다는 DeleteMethod 속성 및 지정 된 매개 변수를 DeleteParameters 컬렉션입니다. 이 코드 예제에서는 몇 가지 전처리 및 후 처리 단계도 수행 됩니다. NorthwindEmployeeDeleting 대리자를 처리 하기 위해 호출 됩니다는 Deleting 작업을 수행 하려면 먼저 이벤트 및 NorthwindEmployeeDeleted 대리자를 처리 하기 위해 호출 됩니다는 Deleted 예외 처리를 수행 하는 작업이 완료 된 후 이벤트입니다. 이 예제의 경우는 NorthwindDataException 는 의해 처리 될 throw는 NorthwindDataException 대리자.

<%@ 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 NorthwindEmployeeDeleting(object source, ObjectDataSourceMethodEventArgs e)
{
  // The GridView passes the ID of the employee
  // to be deleted. However, the buisiness object, EmployeeLogic,
  // requires a NorthwindEmployee parameter, named "ne". Create
  // it now and add it to the parameters collection.
  IDictionary paramsFromPage = e.InputParameters;
  if (paramsFromPage["EmpID"] != null) {
    NorthwindEmployee ne
      = new NorthwindEmployee( Int32.Parse(paramsFromPage["EmpID"].ToString()));
    // Remove the old EmpID parameter.
    paramsFromPage.Clear();
    paramsFromPage.Add("ne", ne);
  }
}

private void NorthwindEmployeeDeleted(object source, ObjectDataSourceStatusEventArgs e)
{
  // Handle the Exception if it is a NorthwindDataException
  if (e.Exception != null)
  {

    // Handle the specific exception type. The ObjectDataSource wraps
    // any Exceptions in a TargetInvokationException wrapper, so
    // check the InnerException property for expected Exception types.
    if (e.Exception.InnerException is NorthwindDataException)
    {
      Label1.Text = e.Exception.InnerException.Message;
      // Because the exception is handled, there is
      // no reason to throw it.
      e.ExceptionHandled = true;
    }
  }
}

</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:gridview
          id="GridView1"
          runat="server"
          datasourceid="ObjectDataSource1"
          autogeneratedeletebutton="true"
          autogeneratecolumns="false"
          datakeynames="EmpID">
          <columns>
            <asp:boundfield headertext="EmpID" datafield="EmpID" />
            <asp:boundfield headertext="First Name" datafield="FirstName" />
            <asp:boundfield headertext="Last Name" datafield="LastName" />
          </columns>
        </asp:gridview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          deletemethod="DeleteEmployee"
          ondeleting="NorthwindEmployeeDeleting"
          ondeleted="NorthwindEmployeeDeleted"
          typename="Samples.AspNet.CS.EmployeeLogic">
          <deleteparameters>
            <asp:parameter name="EmpID" type="Int32" />
          </deleteparameters>
        </asp:objectdatasource>

        <asp:label id="Label1" runat="server" />

    </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">
' Called before a Delete operation.
    Private Sub NorthwindEmployeeDeleting(ByVal source As Object, ByVal e As ObjectDataSourceMethodEventArgs)

        ' The GridView passes the ID of the employee
        ' to be deleted. However, the business object, EmployeeLogic,
        ' requires a NorthwindEmployee parameter, named "ne". Create
        ' it now and add it to the parameters collection.
        Dim paramsFromPage As IDictionary = e.InputParameters
  
        If Not paramsFromPage("EmpID") Is Nothing Then
    
            Dim ne As New NorthwindEmployee(paramsFromPage("EmpID").ToString())
            ' Remove the old EmpID parameter.
            paramsFromPage.Clear()
            paramsFromPage.Add("ne", ne)
    
    
        End If
    End Sub ' NorthwindEmployeeDeleting

    ' Called after a Delete operation.
    Private Sub NorthwindEmployeeDeleted(ByVal source As Object, ByVal e As ObjectDataSourceStatusEventArgs)
        ' Handle the Exception if it is a NorthwindDataException.
        If Not e.Exception Is Nothing Then

            ' Handle the specific exception type. The ObjectDataSource wraps
            ' any Exceptions in a TargetInvokationException wrapper, so
            ' check the InnerException property for the expected Exception types.
            If e.Exception.InnerException.GetType().Equals(GetType(NorthwindDataException)) Then

                Label1.Text = e.Exception.InnerException.Message
                ' Because the exception is handled, there is
                ' no reason to throw it.
                e.ExceptionHandled = True
      
            End If
        End If
    End Sub ' NorthwindEmployeeDeleted
</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:gridview
          id="GridView1"
          runat="server"
          datasourceid="ObjectDataSource1"
          autogeneratedeletebutton="true"
          autogeneratecolumns="false"
          datakeynames="EmpID">
          <columns>
            <asp:boundfield headertext="EmpID" datafield="EmpID" />
            <asp:boundfield headertext="First Name" datafield="FirstName" />
            <asp:boundfield headertext="Last Name" datafield="LastName" />
          </columns>
        </asp:gridview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          deletemethod="DeleteEmployee"
          ondeleting="NorthwindEmployeeDeleting"
          ondeleted="NorthwindEmployeeDeleted"
          typename="Samples.AspNet.VB.EmployeeLogic">
          <deleteparameters>
            <asp:parameter name="EmpID" type="Int32" />
          </deleteparameters>
        </asp:objectdatasource>

        <asp:label id="Label1" runat="server" />

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

다음 코드 예제는 EmployeeLogic 앞의 코드 예제에 사용 되는 클래스입니다.

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();

      // 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) {
      return new NorthwindEmployee(anID);
    }

    public static void DeleteEmployee(NorthwindEmployee ne) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("Employee delete failed."); }
      // Delete the object in memory.
      ne = null;
    }

    public static void DeleteEmployeeByID(int anID) {
        NorthwindEmployee tempEmp = new NorthwindEmployee(anID);
        DeleteEmployee(tempEmp);
    }
  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
    }

    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 " +
                       " 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();
        }
        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 {
      get { return lastName; }
      set { lastName = value; }
    }

    private string firstName;
    public string FirstName {
      get { return firstName; }
      set { firstName = value;  }
    }
    public bool Delete () {
      if (ID.Equals(DBNull.Value)) {
        // The Employee object is not persisted.
        return true;
      }
      else {
        // The Employee object is persisted.
        // Use the SqlDataSource control as a convenient wrapper for
        // the ADO.NET code needed to delete a record from the database.
        ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
        SqlDataSource sds = new SqlDataSource();

        try {
          sds.ConnectionString = cts.ConnectionString;
          sds.DeleteParameters.Add(new Parameter("empID", TypeCode.Int32, this.ID.ToString()));
          sds.DeleteCommand = "DELETE FROM [Order Details] " + 
              "WHERE OrderID IN (SELECT OrderID FROM Orders WHERE EmployeeID=@empID)";
          sds.Delete();
          sds.DeleteCommand = "DELETE FROM Orders WHERE EmployeeID=@empID";
          sds.Delete();
          sds.DeleteCommand = "DELETE FROM EmployeeTerritories WHERE EmployeeID=@empID";
          sds.Delete();
          sds.DeleteCommand = "DELETE FROM Employees WHERE EmployeeID=@empID";
          sds.Delete();
          return true;
        }
        finally {
          // Clean up resources.
          sds.Dispose();
        }
      }
    }
  }

  public 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

   ' Return 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
      Return New NorthwindEmployee(anID)
   End Function 'GetEmployee


   Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Delete()
      If Not retval Then
         Throw New NorthwindDataException("Employee delete failed.")
      End If ' Delete the object in memory.
      ne = Nothing
   End Sub


   Public Shared Sub DeleteEmployeeByID(anID As Integer)
      Dim tempEmp As New NorthwindEmployee(anID)
      DeleteEmployee(tempEmp)
   End Sub

End Class

Public Class NorthwindEmployee

   Public Sub New()
      ID = DBNull.Value
      aLastName = ""
      aFirstName = ""
   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 " & _
                               " 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()
         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 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 Function Delete() As Boolean
      If ID.Equals(DBNull.Value) Then
         ' The Employee object is not persisted.
         Return True
      Else
         ' The Employee object is persisted.
         ' Use the SqlDataSource control as a convenient wrapper for
         ' the ADO.NET code needed to delete a record from the database.
         Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
         Dim sds As New SqlDataSource()
         Try
            sds.ConnectionString = cts.ConnectionString
            sds.DeleteParameters.Add(New Parameter("empID", TypeCode.Int32, Me.ID.ToString()))
            sds.DeleteCommand = "DELETE FROM [Order Details] " & _
                "WHERE OrderID IN (SELECT OrderID FROM Orders WHERE EmployeeID=@empID)"
            sds.Delete()
            sds.DeleteCommand = "DELETE FROM Orders WHERE EmployeeID=@empID"
            sds.Delete()
            sds.DeleteCommand = "DELETE FROM EmployeeTerritories WHERE EmployeeID=@empID"
            sds.Delete()
            sds.DeleteCommand = "DELETE FROM Employees WHERE EmployeeID=@empID"
            sds.Delete()
            Return True
         Finally
            ' Clean up resources.
            sds.Dispose()
         End Try
      End If
   End Function 'Delete
End Class

Public Class NorthwindDataException
   Inherits Exception

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

End Class
End Namespace

설명

비즈니스 개체는 한 번에 아닌 일괄 처리 데이터 하나의 레코드를 삭제로 간주 됩니다.

DeleteMethod 에 위임 하는 속성을 DeleteMethod 의 속성을 ObjectDataSourceView 개체와 연결 된는 ObjectDataSource 컨트롤.

매개 변수 이름에 대 한 구성 되었는지 확인 합니다 ObjectDataSource 에서 제어를 DeleteParameters 컬렉션 select 메서드에 의해 반환 되는 열 이름과 일치 합니다.

개체 수명

로 식별 되는 메서드를 DeleteMethod 속성에는 인스턴스 메서드 일 수 있습니다 또는 static (Shared Visual Basic에서) 메서드. 비즈니스 개체가 만들어지고 제거 될 때마다 인스턴스 메서드인 경우는 DeleteMethod 속성 이라고 합니다. 처리할 수 있습니다 합니다 ObjectCreatedObjectCreating 하기 전에 비즈니스 개체를 사용 하는 이벤트를 DeleteMethod 속성 이라고 합니다. 처리할 수도 있습니다는 ObjectDisposing 후에 발생 하는 이벤트를 DeleteMethod 속성 이라고 합니다. 비즈니스 개체를 구현 하는 경우는 IDisposable 인터페이스는 Dispose 개체를 제거 하기 전에 호출 됩니다. 메서드가 static (Shared Visual Basic의) 메서드를 비즈니스 개체가 생성 되지 않고 처리할 수 없는 합니다 ObjectCreated, ObjectCreating, 및 ObjectDisposing 이벤트.

병합 하는 매개 변수

매개 변수가 추가 됩니다는 DeleteParameters 다음 세 가지 소스의 컬렉션:

  • 런타임에 데이터 바인딩된 컨트롤입니다.

  • DeleteParameters 요소를 선언적으로 합니다.

  • Deleting 메서드를 선언적으로 합니다.

데이터 바인딩된 컨트롤에서 생성 된 모든 매개 변수가 먼저 추가 됩니다는 DeleteParameters 컬렉션입니다. 예를 들어 경우는 ObjectDataSource 컨트롤이 바인딩되는 GridView 열이 있는 컨트롤 NameNumber에 대 한 매개 변수 NameNumber 컬렉션에 추가 됩니다. 매개 변수가의 정확한 이름은 OldValuesParameterFormatString 속성입니다. 이러한 매개 변수의 데이터 형식은 string합니다. 다음으로에 나와 있는 매개 변수는 DeleteParameters 요소가 추가 됩니다. 경우에 매개 변수를 DeleteParameters 에 이미 있는 매개 변수로 동일한 이름을 가진 요소가 DeleteParameters 기존 매개 변수 컬렉션에 지정 된 매개 변수와 일치 하도록 수정 됩니다는 DeleteParameters 요소. 일반적으로이 매개 변수의 데이터 형식을 수정 하려면 사용 됩니다. 마지막으로 프로그래밍 방식으로 추가 및 제거할 수의 매개 변수를 Deleting 하기 전에 발생 하는 이벤트를 Delete 메서드를 실행 합니다. 메서드는 매개 변수를 병합 된 후 확인 됩니다. 메서드 확인은 다음 섹션에 설명 되어 있습니다.

메서드 확인

경우는 Delete 메서드를 호출할 매개 변수에서 선언적으로 생성 된 데이터 바인딩된 컨트롤에서 데이터 필드를 DeleteParameters 요소 및에 추가 된 매개 변수는 Deleting 이벤트 처리기 모두 병합 됩니다. (자세한 내용은 이전 섹션 참조). ObjectDataSource 개체 호출할 메서드를 찾으려고 시도 합니다. 에 지정 된 이름 가진 하나 이상의 메서드를 찾습니다 먼저는 DeleteMethod 속성입니다. 일치 하는 항목이 없으면는 InvalidOperationException 예외가 throw 됩니다. 일치 하는 항목이 있으면 매개 변수 이름과 일치 하는 찾습니다. 예를 들어 지정 된 형식 합니다 TypeName 속성이 라는 두 개의 메서드도 DeleteARecord합니다. 하나의 DeleteARecord 하나의 매개 변수가 ID, 및 다른 DeleteARecord 두 매개 변수가 NameNumber합니다. 경우는 DeleteParameters 컬렉션에 명명 된 매개 변수만 IDDeleteARecord 메서드를만 ID 매개 변수 라고 합니다. 메서드를 확인 하는 데 매개 변수의 형식을 확인 하지 않습니다. 매개 변수의 순서는 중요 하지 않습니다.

경우는 DataObjectTypeName 속성, 메서드를 다른 방식으로 확인 됩니다. ObjectDataSource 에 지정 된 이름의 메서드를 찾습니다는 DeleteMethod 는 매개 변수 형식 중 하나를 사용 하는 속성에 지정 된 된 DataObjectTypeName 속성. 이 경우 매개 변수의 이름을 중요 하지 않습니다.

적용 대상

추가 정보