ObjectDataSource.DeleteParameters 属性

定义

获取参数集合,该集合包含由 DeleteMethod 方法使用的参数。

public:
 property System::Web::UI::WebControls::ParameterCollection ^ DeleteParameters { System::Web::UI::WebControls::ParameterCollection ^ get(); };
[System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)]
public System.Web.UI.WebControls.ParameterCollection DeleteParameters { get; }
[<System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)>]
member this.DeleteParameters : System.Web.UI.WebControls.ParameterCollection
Public ReadOnly Property DeleteParameters As ParameterCollection

属性值

ParameterCollection,包含由 DeleteMethod 方法使用的参数。

属性

示例

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

下面的代码示例演示如何将 DeleteParameters 控件的 ObjectDataSource 属性与业务对象和控件一 GridView 起使用以删除数据。 最初, GridView 控件显示一组所有员工,使用 属性 SelectMethod 指定的 方法从 EmployeeLogic 对象检索数据。 由于 属性 AutoGenerateDeleteButton 设置为 true,因此控件 GridView 会自动显示 “删除” 按钮。

如果单击“ 删除” 按钮,则会 Deleting 使用两个参数调用事件。 一个参数 EmpID来自 DataGrid 控件,基于 DataKeyNames 属性。 另一个参数来自声明性 DeleteParameters 属性。 类 EmployeeLogic 重载 DeleteEmployee 方法。 一个 NorthwindEmployee 重载采用参数,另一个 Int32 重载采用名为 的参数 anID。 在 事件中 Deleting ,将调整 属性中的 InputParameters 条目,以仅包含一个名为 的参数 anID 以及 来自 original_EmpID的值。 当事件处理程序存在时,将调用匹配 DeleteEmployee 方法。

下面的代码示例演示显示 DataGrid 控件并处理 事件的 Deleting 网页。

<%@ 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)
{
  IDictionary paramsFromPage = e.InputParameters;

  paramsFromPage.Remove("anID");
  paramsFromPage.Add("anID", (int)paramsFromPage["EmpID"]);
  paramsFromPage.Remove("EmpID");
    
}
</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"
          DataKeyNames="EmpID">
        </asp:gridview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          deletemethod="DeleteEmployee"
          OnDeleting="NorthwindEmployeeDeleting"
          typename="Samples.AspNet.CS.EmployeeLogic">
          <deleteparameters>
            <asp:parameter name="anID" type="Int32" />
          </deleteparameters>
        </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 NorthwindEmployeeDeleting(source As Object, e As ObjectDataSourceMethodEventArgs)

  Dim paramsFromPage As IDictionary = e.InputParameters

  paramsFromPage.Remove("anID")
  paramsFromPage.Add("anID", CInt(paramsFromPage("EmpID")))
  paramsFromPage.Remove("EmpID")

End Sub ' NorthwindEmployeeDeleting
</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"
          DataKeyNames="EmpID">
        </asp:gridview>

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

    </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;
          int id = (int) row["EmployeeID"];
          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(int 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 DeleteEmployee(int anID) {
        NorthwindEmployee tempEmp = new NorthwindEmployee(anID);
        DeleteEmployee(tempEmp);
    }
  }
  public class NorthwindEmployee {

    public NorthwindEmployee (int 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()));

          /* To make this sample fully functional, uncomment these lines
          int retval = sds.Delete();
          if (retval == 1) { return true; }
          return false; */

          return true;
        }
        finally {
          sds.Dispose();
        }
      }
    }
  }
  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()

      ' 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(CInt(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 Integer) 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 DeleteEmployee(anID As Integer)
      Dim tempEmp As New NorthwindEmployee(anID)
      DeleteEmployee(tempEmp)
   End Sub

   ' And so on...

End Class

Public Class NorthwindEmployee

   Public Sub New(anID As Integer)
      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.firstName = sdr("FirstName").ToString()
            Me.lastName = 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.DeleteCommand = "DELETE FROM Employees WHERE EmployeeID=@empID;"
                    Dim param As New Parameter("empID", TypeCode.Int32, CStr(Me.ID))
            sds.DeleteParameters.Add(param)

            ' To make this sample fully functional, uncomment these lines
'          int retval = sds.Delete();
'          if (retval == 1) { return true; }
'          return false;

            Return True
         Finally
            sds.Dispose()
         End Try
      End If
   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

注解

集合中包含的 DeleteParameters 参数的名称和类型必须与方法签名中 DeleteMethod 参数的名称和类型匹配。 参数名称受 OldValuesParameterFormatString 属性影响,并且区分大小写。 集合中的参数取决于数据绑定控件中的数据、以声明方式指定的参数以及以编程方式添加的参数。 有关详细信息,请参阅 和 将参数与 ObjectDataSource 控件配合使用中的Delete“参数合并”。

属性 DeleteParameters 检索 DeleteParametersObjectDataSourceView 与 控件关联的 对象包含的属性 ObjectDataSource

有关参数合并、对象生存期和方法解析的详细信息,请参阅 DeleteMethod

适用于

另请参阅