ObjectDataSourceStatusEventArgs 類別

定義

提供 Selected 控制項之 InsertedUpdatedDeletedObjectDataSource 事件的資料。

public ref class ObjectDataSourceStatusEventArgs : EventArgs
public class ObjectDataSourceStatusEventArgs : EventArgs
type ObjectDataSourceStatusEventArgs = class
    inherit EventArgs
Public Class ObjectDataSourceStatusEventArgs
Inherits EventArgs
繼承
ObjectDataSourceStatusEventArgs

範例

本節包含兩個程式碼範例。 第一個 ObjectDataSource 程式碼範例示範如何使用控制項搭配商務物件和 GridView 控制項來刪除資料。 第二個程式碼範例提供第一個程式碼範例所使用的仲介層商務物件範例。

下列程式碼範例示範如何使用 ObjectDataSource 控制項搭配商務物件和 GridView 控制項來刪除資料。 一 GridView 開始會使用 屬性所 SelectMethod 指定的 方法來擷 EmployeeLogic 取 物件中的資料,顯示一組所有員工。 AutoGenerateDeleteButton因為 屬性設定為 true ,所以 GridView 控制項會自動顯示 [刪除]按鈕。

如果您按一下 [ 刪除] 按鈕,則會 Delete 使用 屬性所 DeleteMethod 指定的 方法和集合中指定的 DeleteParameters 任何參數來執行動作。 在此程式碼範例中,集合中 DeleteParameters 會指定一個對應至員工識別碼的參數。 這是因為雖然識別碼包含在集合中 Columns 做為 BoundField 物件,但它會當做字串傳遞至 ObjectDataSource 控制項。 藉由將它明確新增至 DeleteParameters 集合,並將 Type 屬性設定為 Int32 值,它會以整數的形式將 它正確地傳遞給 ObjectDataSource 方法,而不是字串。

在此程式碼範例中,也會執行一些前置處理和後置處理步驟。 呼叫 NorthwindEmployeeDeleting 委派以在執行動作之前 Delete 處理 Deleting 事件,並 NorthwindEmployeeDeleted 呼叫委派來處理 Deleted 動作 Delete 完成後的事件,以處理可能發生的任何例外狀況。 委派 NorthwindEmployeeDeleted 會存取使用 ObjectDataSourceStatusEventArgs 物件之商務物件擲回的可能例外狀況。 在此範例中,如果 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 是不會維護狀態並封裝商務邏輯的類別。

  • 類別 NorthwindEmployee 是模型類別,只包含從資料層載入和保存資料所需的基本功能。

此外,類別 NorthwindDataException 會以方便的方式提供。

這組範例類別使用 Northwind Traders 資料庫,這是 Microsoft SQL Server 和 Microsoft Access 提供的範例資料庫。 如需完整的工作範例,您必須將此程式碼編譯為程式庫,然後從 ASP 頁面使用這些類別。 上述範例中提供的 ASP 頁面設定為使用此類別庫。 方法 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();

      // 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

備註

類別 ObjectDataSourceStatusEventArgs 用於 OnSelectedOnUpdatedOnInsertedOnDeleted 方法,以提供控制項所呼叫方法所擲回之輸出參數、傳回值和例外狀況的 ObjectDataSource 存取權。 這些分別由 OutputParametersReturnValueException 屬性存取。 藉由新增委派來處理 SelectedUpdatedInsertedDeleted 事件,您可以檢查此資料,並執行所需的任何其他後續處理。

控制項 ObjectDataSource 會公開許多事件,您可以處理這些事件,以在其生命週期的各個時間使用基礎商務物件。 下表列出事件和相關聯的 EventArgs 類別和事件處理常式委派。

事件 EventArgs EventHandler
ObjectCreating.

會在建立商務物件的實例之前立即發生。
ObjectDataSourceEventArgs ObjectDataSourceObjectEventHandler
ObjectCreated.

會在建立商務物件的實例之後立即發生。
ObjectDataSourceEventArgs ObjectDataSourceObjectEventHandler
Selecting.

發生于擷取資料之前。
ObjectDataSourceSelectingEventArgs ObjectDataSourceSelectingEventHandler
InsertingUpdatingDeleting

發生于執行插入、更新或刪除作業之前。
ObjectDataSourceMethodEventArgs ObjectDataSourceMethodEventHandler
Selected.

發生于擷取資料之後。
ObjectDataSourceStatusEventArgs ObjectDataSourceStatusEventHandler
InsertedUpdatedDeleted

發生于插入、更新或刪除作業完成之後。
ObjectDataSourceStatusEventArgs ObjectDataSourceStatusEventHandler
ObjectDisposing.

在終結商務物件之前發生。
ObjectDataSourceDisposingEventArgs ObjectDataSourceDisposingEventHandler

建構函式

ObjectDataSourceStatusEventArgs(Object, IDictionary)

使用指定的輸出參數和傳回值,初始化 ObjectDataSourceStatusEventArgs 類別的新執行個體。

ObjectDataSourceStatusEventArgs(Object, IDictionary, Exception)

使用指定的輸出參數、傳回值和例外狀況,初始化 ObjectDataSourceStatusEventArgs 類別的新執行個體。

屬性

AffectedRows

取得或設定受到資料作業影響的資料列數目。

Exception

取得在資料作業期間由 ObjectDataSource 控制項呼叫的方法所擲回之任何例外狀況的包裝函式。

ExceptionHandled

取得或設定值,表示是否已處理商務物件擲回的例外狀況。

OutputParameters

取得包含商務物件方法參數和其值的集合。

ReturnValue

取得商務物件方法傳回之做為物件的傳回值 (如果有的話)。

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

另請參閱