ObjectDataSource.DeleteMethod 属性

注意:此属性在 .NET Framework 2.0 版中是新增的。

获取或设置由 ObjectDataSource 控件调用以删除数据的方法或函数的名称。

命名空间:System.Web.UI.WebControls
程序集:System.Web(在 system.web.dll 中)

[@more@] 语法
Visual Basic(声明)
Public Property DeleteMethod As String
Visual Basic(用法)
Dim instance As ObjectDataSource
Dim value As String

value = instance.DeleteMethod

instance.DeleteMethod = value
C#
public string DeleteMethod { get; set; }
C++
public:
property String^ DeleteMethod {
    String^ get ();
    void set (String^ value);
}
J#
/** @property */
public String get_DeleteMethod ()

/** @property */
public void set_DeleteMethod (String value)
JScript
public function get DeleteMethod () : String

public function set DeleteMethod (value : String)

属性值
一个字符串,表示由 ObjectDataSource 用来删除数据的方法或函数的名称。默认值为空字符串 ("")。 备注备注

假定业务对象以逐个记录(而不是以批处理)的方式删除数据。

DeleteMethod 属性委托给与 ObjectDataSource 控件关联的

对象生存期

DeleteMethod 属性标识的方法可以是实例方法或 static(在 Visual Basic 中为 Shared)方法。如果它是实例方法,则在每次调用 DeleteMethod 属性时都会创建并销毁业务对象。您可以处理 和 事件,在调用 DeleteMethod 属性之前使用业务对象。还可以处理在调用 DeleteMethod 属性之后引发的 事件。如果业务对象实现 接口,则在销毁该对象前调用 方法。如果方法是 static(在 Visual Basic 中为 Shared)方法,则从不创建业务对象,而且您无法处理 ObjectCreatedObjectCreatingObjectDisposing 事件。

参数合并

参数从三个来源添加到 集合中:

从数据绑定控件(在运行时)。

DeleteParameters 元素(以声明方式)。

Deleting 方法(以声明方式)。

首先,将通过数据绑定控件生成的所有参数添加到 DeleteParameters 集合中。例如,如果 ObjectDataSource 控件绑定到具有列 NameNumber 的 控件,则将 NameNumber 的参数添加到集合中。参数的确切名称取决于 属性。这些参数的数据类型是 string。然后,添加 DeleteParameters 元素中列出的参数。如果 DeleteParameters 元素中的参数与 DeleteParameters 集合中的现有参数同名,则修改现有参数以与 DeleteParameters 元素中指定的参数匹配。这通常用于修改参数中的数据类型。最后,可以在 事件中以编程方式添加和移除参数,该事件在 方法运行前发生。合并参数后解析方法。下一节讨论方法解析。

方法解析

调用 Delete 方法时,数据绑定控件中的数据字段、DeleteParameters 元素中以声明方式创建的参数和 Deleting 事件处理程序中添加的参数全部合并在一起。(有关更多信息,请参见上一节。)然后,ObjectDataSource 对象尝试查找可以调用的方法。首先,它查找具有 DeleteMethod 属性中指定的名称的一个或多个方法。如果没有找到匹配项,则引发 异常。如果找到了匹配项,它随后将查找匹配的参数名。例如,假设 属性指定的类型有两个名为 DeleteARecord 的方法。一个 DeleteARecord 带一个参数 ID,另一个 DeleteARecord 带两个参数 NameNumber。如果 DeleteParameters 集合只包含一个名为 ID 的参数,则调用仅带 ID 参数的 DeleteARecord 方法。解析方法时不检查参数类型。参数的顺序无关紧要。

如果设置了 属性,将以不同的方式解析方法。ObjectDataSource 查找具有 DeleteMethod 属性中指定的名称的方法,该属性带 DataObjectTypeName 属性中指定的类型的一个参数。这种情况下,参数的名称无关紧要。

TopicLocation生成 ASP .NET Web 应用程序
ObjectDataSourceView 对象的 DeleteMethod 属性。
示例示例

本节包含两个代码示例。第一个代码示例演示如何将 ObjectDataSource 对象与业务对象和 GridView 控件一起使用来删除数据。第二个代码示例演示在第一个代码示例中使用的 EmployeeLogic 类。

下面的代码示例演示如何将 ObjectDataSource 控件与业务对象和 GridView 控件配合使用来删除数据。GridView 控件最初使用由

如果单击“删除”按钮,则使用由 DeleteMethod 属性指定的方法和 DeleteParameters 集合中指定的任何参数来执行删除操作。在此代码示例中,还执行了一些预处理和后续处理步骤。在执行操作之前调用 NorthwindEmployeeDeleting 委托来处理 Deleting 事件,并在操作完成之后调用 NorthwindEmployeeDeleted 委托来处理 事件,以便执行异常处理。在此示例中,如果引发 NorthwindDataException,将由 NorthwindDataException 委托来处理此异常。

Visual Basic
"aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
namespace="Samples.AspNet.VB" %>
"vb" %>
ObjectDataSource - VB Example
"Form1" method="post" runat="server"> "GridView1" runat="server" datasourceid="ObjectDataSource1" autogeneratedeletebutton="true" autogeneratecolumns="false" datakeynames="EmpID"> "EmpID" datafield="EmpID" /> "First Name" datafield="FirstName" /> "Last Name" datafield="LastName" /> "ObjectDataSource1" runat="server" selectmethod="GetAllEmployees" deletemethod="DeleteEmployee" ondeleting="NorthwindEmployeeDeleting" ondeleted="NorthwindEmployeeDeleted" typename="Samples.AspNet.VB.EmployeeLogic"> "EmpID" type="Int32" /> "Label1" runat="server" />
C#
"aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
namespace="Samples.AspNet.CS" %>
"c#" %>
ObjectDataSource - C# Example
"Form1" method="post" runat="server"> "GridView1" runat="server" datasourceid="ObjectDataSource1" autogeneratedeletebutton="true" autogeneratecolumns="false" datakeynames="EmpID"> "EmpID" datafield="EmpID" /> "First Name" datafield="FirstName" /> "Last Name" datafield="LastName" /> "ObjectDataSource1" runat="server" selectmethod="GetAllEmployees" deletemethod="DeleteEmployee" ondeleting="NorthwindEmployeeDeleting" ondeleted="NorthwindEmployeeDeleted" typename="Samples.AspNet.CS.EmployeeLogic"> "EmpID" type="Int32" /> "Label1" runat="server" />

下面的代码示例显示了前面的代码示例中使用的 EmployeeLogic 类。

Visual Basic
Imports System
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 'DeleteEmployee


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

End Class 'EmployeeLogic

Public Class NorthwindEmployee

   Public Sub New()
      ID = DBNull.Value
      aLastName = ""
      aFirstName = ""
   End Sub 'New


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

   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.DeleteCommand = "DELETE FROM Employees WHERE EmployeeID=@empID"
            sds.DeleteParameters.Add(New Parameter("empID", TypeCode.Int32, Me.ID.ToString()))

            ' Implement the remainder of the Delete() method.
            '
            Throw New NorthwindDataException("Delete() method not completely implemented.")

            Return True
         Finally
            ' Clean up resources.
            sds.Dispose()
         End Try
      End If
   End Function 'Delete
End Class 'NorthwindEmployee

Public Class NorthwindDataException
   Inherits Exception

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

End Class 'NorthwindDataException
End Namespace
C#
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.DeleteCommand = "DELETE FROM Employees WHERE EmployeeID=@empID";
          sds.DeleteParameters.Add(new Parameter("empID",TypeCode.Int32,this.ID.ToString()));

          //
          // Implement the remainder of the Delete() method.
          //
          throw new NorthwindDataException("Delete() method not completely implemented.");
        }
        finally {
          // Clean up resources.
          sds.Dispose();
        }
      }
    }
  }

  public class NorthwindDataException: Exception {
    public NorthwindDataException(string msg) : base (msg) { }
  }
}
SelectMethod 属性指定的方法从 EmployeeLogic 对象中检索数据,以显示所有雇员的集合。由于 AutoGenerateDeleteButton 属性设置为 true,因此 GridView 控件会自动显示“删除”按钮。
平台平台

Windows 98、Windows 2000 SP4、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见

系统要求

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10771986/viewspace-969646/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10771986/viewspace-969646/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值