ObjectDataSource.DeleteMethod Proprietà

Definizione

Ottiene o imposta il nome del metodo o funzione che il controllo ObjectDataSource richiama per eliminare dati.

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

Valore della proprietà

Stringa che rappresenta il nome del metodo o funzione che l'oggetto ObjectDataSource utilizza per eliminare i dati. Il valore predefinito è una stringa vuota ("").

Esempio

In questa sezione sono riportati due esempi di codice. Il primo esempio di codice illustra come usare un oggetto con un ObjectDataSource oggetto business e un GridView controllo per eliminare i dati. Il secondo esempio di codice mostra la EmployeeLogic classe usata nel primo esempio di codice.

Nell'esempio di codice seguente viene illustrato come usare un controllo con un ObjectDataSource oggetto business e un GridView controllo per eliminare i dati. Inizialmente, il controllo visualizza un set di tutti i dipendenti, usando il GridView metodo specificato dalla SelectMethod proprietà per recuperare i dati dall'oggetto EmployeeLogic . Poiché la AutoGenerateDeleteButton proprietà è impostata su true, il GridView controllo visualizza automaticamente un pulsante Delete .

Se si fa clic sul pulsante Delete , l'operazione di eliminazione viene eseguita usando il metodo specificato dalla DeleteMethod proprietà e tutti i parametri specificati nella DeleteParameters raccolta. In questo esempio di codice vengono eseguiti anche alcuni passaggi di pre-elaborazione e post-elaborazione. Il NorthwindEmployeeDeleting delegato viene chiamato per gestire l'evento Deleting prima dell'esecuzione dell'operazione e il NorthwindEmployeeDeleted delegato viene chiamato per gestire l'evento Deleted dopo il completamento dell'operazione per eseguire la gestione delle eccezioni. In questo esempio, se viene generato un NorthwindDataException oggetto, viene gestito dal NorthwindDataException delegato.

<%@ 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>

Nell'esempio di codice seguente viene illustrata la classe usata nell'esempio EmployeeLogic di codice precedente.

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

Commenti

Si presuppone che l'oggetto business elimini i dati un record alla volta, anziché in un batch.

La DeleteMethod proprietà delega alla DeleteMethod proprietà dell'oggetto ObjectDataSourceView associato al ObjectDataSource controllo.

Assicurarsi che i nomi dei parametri configurati per il ObjectDataSource controllo nella DeleteParameters raccolta corrispondano ai nomi di colonna restituiti dal metodo select.

Durata dell'oggetto

Il metodo identificato dalla DeleteMethod proprietà può essere un metodo di istanza o un static metodo (Shared in Visual Basic). Se si tratta di un metodo di istanza, l'oggetto business viene creato e eliminato ogni volta che viene chiamata la DeleteMethod proprietà. È possibile gestire gli ObjectCreated eventi e ObjectCreating per usare l'oggetto business prima che venga chiamata la DeleteMethod proprietà. È anche possibile gestire l'evento ObjectDisposing generato dopo la chiamata della DeleteMethod proprietà. Se l'oggetto business implementa l'interfaccia IDisposable , il Dispose metodo viene chiamato prima che l'oggetto venga distrutto. Se il metodo è un static metodo (Shared in Visual Basic), l'oggetto business non viene mai creato e non è possibile gestire gli ObjectCreatedeventi , ObjectCreatinge ObjectDisposing .

Unione dei parametri

I parametri vengono aggiunti alla DeleteParameters raccolta da tre origini:

  • Dal controllo associato a dati, in fase di esecuzione.

  • Dall'elemento DeleteParameters dichiarativo.

  • Deleting Dal metodo, dichiarativo.

Prima di tutto, tutti i parametri generati dai controlli associati ai dati vengono aggiunti alla DeleteParameters raccolta. Ad esempio, se il ObjectDataSource controllo è associato a un GridView controllo con le colonne Name e , i parametri per Name e NumberNumbervengono aggiunti alla raccolta. Il nome esatto del parametro dipende dalla OldValuesParameterFormatString proprietà. Il tipo di dati di questi parametri è string. I parametri elencati nell'elemento DeleteParameters vengono quindi aggiunti. Se viene trovato un parametro nell'elemento DeleteParameters con lo stesso nome di un parametro già presente nell'insieme DeleteParameters , il parametro esistente viene modificato per corrispondere al parametro specificato nell'elemento DeleteParameters . In genere, questa operazione viene usata per modificare il tipo di dati nel parametro. Infine, è possibile aggiungere e rimuovere parametri a livello di codice nell'evento, che si verifica prima dell'esecuzione Deleting del Delete metodo. Il metodo viene risolto dopo l'unione dei parametri. La risoluzione dei metodi viene illustrata nella sezione successiva.

Risoluzione dei metodi

Quando viene chiamato il Delete metodo, i campi dati dal controllo associato ai dati, i parametri creati in modo dichiarativo nell'elemento DeleteParameters e i parametri aggiunti nel Deleting gestore eventi sono tutti uniti. Per altre informazioni, vedere la sezione precedente. L'oggetto ObjectDataSource tenta quindi di trovare un metodo da chiamare. In primo luogo, cerca uno o più metodi con il nome specificato nella DeleteMethod proprietà. Se non viene trovata alcuna corrispondenza, viene generata un'eccezione InvalidOperationException . Se viene trovata una corrispondenza, cerca i nomi dei parametri corrispondenti. Si supponga, ad esempio, che il tipo specificato dalla TypeName proprietà disponga di due metodi denominati DeleteARecord. Uno DeleteARecord ha un parametro, ID, e l'altro DeleteARecord ha due parametri Name e Number. Se l'insieme DeleteParameters ha un solo parametro denominato ID, il metodo con solo il DeleteARecordID parametro viene chiamato. Il tipo del parametro non viene controllato nella risoluzione dei metodi. L'ordine dei parametri non è importante.

Se la DataObjectTypeName proprietà è impostata, il metodo viene risolto in modo diverso. Cerca ObjectDataSource un metodo con il nome specificato nella DeleteMethod proprietà che accetta un parametro del tipo specificato nella DataObjectTypeName proprietà . In questo caso, il nome del parametro non è importante.

Si applica a

Vedi anche