ObjectDataSourceMethodEventArgs ObjectDataSourceMethodEventArgs ObjectDataSourceMethodEventArgs ObjectDataSourceMethodEventArgs Class

Определение

Предоставляет данные для событий Inserting, Updating и Deleting элемента управления ObjectDataSource.Provides data for the Inserting, Updating, and Deleting events of the ObjectDataSource control.

public ref class ObjectDataSourceMethodEventArgs : System::ComponentModel::CancelEventArgs
public class ObjectDataSourceMethodEventArgs : System.ComponentModel.CancelEventArgs
type ObjectDataSourceMethodEventArgs = class
    inherit CancelEventArgs
Public Class ObjectDataSourceMethodEventArgs
Inherits CancelEventArgs
Наследование
ObjectDataSourceMethodEventArgsObjectDataSourceMethodEventArgsObjectDataSourceMethodEventArgsObjectDataSourceMethodEventArgs
Производный

Примеры

Этот раздел содержит два примера кода.This section contains two code examples. В первом примере кода демонстрируется использование ObjectDataSource управления с бизнес-объект и DetailsView управления для вставки данных.The first code example demonstrates how to use an ObjectDataSource control with a business object and a DetailsView control to insert data. Второй пример кода предоставляет пример среднего уровня бизнес-объект, используемый в первом примере кода.The second code example provides an example middle-tier business object that is used by the first code example.

В следующем примере кода демонстрируется использование ObjectDataSource управления с бизнес-объект и DetailsView управления для вставки данных.The following code example demonstrates how to use an ObjectDataSource control with a business object and a DetailsView control to insert data. DetailsView Изначально отображает новый NorthwindEmployee записей, а также автоматически созданный вставить кнопки.The DetailsView initially displays a new NorthwindEmployee record, along with an automatically generated Insert button. После ввода данных в поля DetailsView управлять, щелкните вставить кнопку и InsertMethod свойство определит, какой метод выполняет Insert действие.After you enter data into the fields of the DetailsView control, click the Insert button, and the InsertMethod property will identify which method performs the Insert action.

В этом примере UpdateEmployeeInfo метод используется для выполнения инструкции insert; Однако он требует NorthwindEmployee параметр для вставки данных.In this example, the UpdateEmployeeInfo method is used to perform an insert; however, it requires a NorthwindEmployee parameter to insert the data. По этой причине коллекцию строк, DetailsView передает элемент управления автоматически не является достаточным.For this reason, the collection of strings that the DetailsView control passes automatically is not sufficient. NorthwindEmployeeInserting Делегат является ObjectDataSourceMethodEventHandler объект, который обрабатывает Inserting событий и позволяет управлять входных параметров перед Insert операции продолжается.The NorthwindEmployeeInserting delegate is an ObjectDataSourceMethodEventHandler object that handles the Inserting event and enables you to manipulate the input parameters before the Insert operation proceeds. Так как UpdateEmployeeInfo метод требует NorthwindEmployee объекта в виде параметра, один создается с помощью коллекции строк и добавляется к InputParameters коллекции.Because the UpdateEmployeeInfo method requires a NorthwindEmployee object as a parameter, one is created using the collection of strings and is added to the InputParameters collection.

<%@ 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 NorthwindEmployeeInserting(object source, ObjectDataSourceMethodEventArgs e)
{
  // The business object expects a custom type. Build it
  // and add it to the parameters collection.
  
  IDictionary paramsFromPage = e.InputParameters;

  NorthwindEmployee ne = new NorthwindEmployee();

  ne.FirstName  = paramsFromPage["FirstName"].ToString();
  ne.LastName   = paramsFromPage["LastName"].ToString();
  ne.Title      = paramsFromPage["Title"].ToString();
  ne.Courtesy   = paramsFromPage["Courtesy"].ToString();
  ne.Supervisor = Int32.Parse(paramsFromPage["Supervisor"].ToString());

  paramsFromPage.Clear();
  paramsFromPage.Add("ne", ne);
}

</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:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.CS.EmployeeLogic"
          >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </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 NorthwindEmployeeInserting(source As Object, e As ObjectDataSourceMethodEventArgs)

  ' The GridView control passes an array of strings in the parameters
  ' collection because that is the type it knows how to work with.
  ' However, the business object expects a custom type. Build it
  ' and add it to the parameters collection.
  Dim paramsFromPage As IDictionary = e.InputParameters

  Dim ne As New NorthwindEmployee()
  ne.FirstName  = paramsFromPage("FirstName").ToString()
  ne.LastName   = paramsFromPage("LastName").ToString()
  ne.Title      = paramsFromPage("Title").ToString()
  ne.Courtesy   = paramsFromPage("Courtesy").ToString()
  ne.Supervisor = Int32.Parse(paramsFromPage("Supervisor").ToString())
  
  paramsFromPage.Clear()
  paramsFromPage.Add("ne", ne)
End Sub ' NorthwindEmployeeInserting

</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:detailsview
          id="DetailsView1"
          runat="server"
          autogenerateinsertbutton="True"
          datasourceid="ObjectDataSource1">
        </asp:detailsview>

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetEmployee"
          insertmethod="UpdateEmployeeInfo"
          oninserting="NorthwindEmployeeInserting"
          typename="Samples.AspNet.VB.EmployeeLogic" >
          <selectparameters>
            <asp:parameter name="anID" defaultvalue="-1" />
          </selectparameters>
        </asp:objectdatasource>

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

В следующем примере кода предоставляет среднего уровня бизнес-объект-пример, в предыдущем примере кода.The following code example provides an example middle-tier business object that the preceding code example uses. Ниже описаны две основные классы, которые определены в примере кода.The following list describes the two major classes that are defined in the code example:

  • EmployeeLogic Класс, который является классом без отслеживания состояния, который инкапсулирует бизнес-логики.The EmployeeLogic class, which is a stateless class that encapsulates business logic.

  • NorthwindEmployee Класс, который является классом модели, который содержит только базовые функциональные возможности, необходимые для загрузки и сохранения данных на уровне данных.The NorthwindEmployee class, which is a model class that contains only the basic functionality that is required to load and persist data from the data tier.

Кроме того NorthwindDataException класс предоставляется для удобства.In addition, a NorthwindDataException class is provided as a convenience.

Этот набор классов в примере используется база данных Northwind Traders, — пример базы данных, доступных в Microsoft SQL Server и Microsoft Access.This set of example classes uses the Northwind Traders database, which is an example database available with Microsoft SQL Server and Microsoft Access. Полный рабочий пример используйте эти классы, поместив их в каталоге App_Code в корневом каталоге приложения или скомпилировать их и поместить получившийся файл DLL в каталог Bin.For a complete working example, use these classes by placing them in the App_Code directory under the application root or by compiling them and placing the resulting DLL in the Bin directory. UpdateEmployeeInfo Метод не реализован полностью, поэтому не будет вставлять данные в базе данных Northwind Traders, Экспериментируя с этим примером.The UpdateEmployeeInfo method is not completely implemented, so you will not insert data into the Northwind Traders database when you experiment with this example.

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

      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) {
      if (anID.Equals("-1") ||
          anID.Equals(DBNull.Value) ) {
        return new NorthwindEmployee();
      }
      else {
        return new NorthwindEmployee(anID);
      }
    }

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
      bool retval = ne.Save();
      if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
    }

    public static void DeleteEmployee(NorthwindEmployee ne) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("DeleteEmployee failed."); }
    }

    // And so on...
  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
      title="";
      titleOfCourtesy = "";
      reportsTo = -1;
    }

    public NorthwindEmployee (object anID) {
      this.ID = anID;

      SqlConnection conn
        = new SqlConnection (ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " 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();

        // Only loop once.
        if (sdr != null && sdr.Read()) {
          // The IEnumerable contains DataRowView objects.
          this.firstName        = sdr["FirstName"].ToString();
          this.lastName         = sdr["LastName"].ToString();
          this.title            = sdr["Title"].ToString();
          this.titleOfCourtesy  = sdr["TitleOfCourtesy"].ToString();
          if (! sdr.IsDBNull(4)) {
            this.reportsTo        = sdr.GetInt32(4);
          }
        }
        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 string EmpID {
      get { return ID.ToString();  }
    }

    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 string FullName {
      get { return FirstName + " " + LastName; }
    }

    private string title;
    public String Title {
      get { return title; }
      set { title = value; }
    }

    private string titleOfCourtesy;
    public string Courtesy {
      get { return titleOfCourtesy; }
      set { titleOfCourtesy = value; }
    }

    private int    reportsTo;
    public int Supervisor {
      get { return reportsTo; }
      set { reportsTo = value; }
    }

    public bool Save () {
      // Implement persistence logic.
      return true;
    }

    public bool Delete () {
      // Implement delete logic.
      return true;
    }
  }

  internal class NorthwindDataException: Exception {
    public NorthwindDataException(string msg) : base (msg) { }
  }
}
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

   ' Returns a collection of NorthwindEmployee objects.
   Public Shared Function GetAllEmployees() As ICollection

      Dim al As New ArrayList()

      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
      If anID.Equals("-1") OrElse anID.Equals(DBNull.Value) Then
         Return New NorthwindEmployee()
      Else
         Return New NorthwindEmployee(anID)
      End If
   End Function 'GetEmployee


   Public Shared Sub UpdateEmployeeInfo(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Save()
      If Not retval Then
         Throw New NorthwindDataException("UpdateEmployee failed.")
      End If
   End Sub 'UpdateEmployeeInfo

   Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
      Dim retval As Boolean = ne.Delete()
      If Not retval Then
         Throw New NorthwindDataException("DeleteEmployee failed.")
      End If
   End Sub 'DeleteEmployee

   ' And so on...

End Class 'EmployeeLogic


Public Class NorthwindEmployee


   Public Sub New()
      ID = DBNull.Value
      lastName = ""
      firstName = ""
      title = ""
      titleOfCourtesy = ""
      reportsTo = - 1
   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,Title,TitleOfCourtesy,ReportsTo " & _
                               " 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()

         ' Only loop 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()
            Me.aTitle = sdr("Title").ToString()
            Me.titleOfCourtesy = sdr("TitleOfCourtesy").ToString()
            If Not sdr.IsDBNull(4) Then
               Me.reportsTo = sdr.GetInt32(4)
            End If
         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 String
      Get
         Return ID.ToString()
      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 ReadOnly Property FullName() As String
      Get
         Return FirstName & " " & LastName
      End Get
   End Property

   Private aTitle As String
   Public Property Title() As String
      Get
         Return aTitle
      End Get
      Set
         aTitle = value
      End Set
   End Property

   Private titleOfCourtesy As String
   Public Property Courtesy() As String
      Get
         Return titleOfCourtesy
      End Get
      Set
         titleOfCourtesy = value
      End Set
   End Property

   Private reportsTo As Integer
   Public Property Supervisor() As Integer
      Get
         Return reportsTo
      End Get
      Set
         reportsTo = value
      End Set
   End Property

   Public Function Save() As Boolean

      ' Implement persistence logic.
      Return True

   End Function 'Save


   Public Function Delete() As Boolean

     ' Implement delete logic.
     Return True

   End Function 'Delete
End Class 'NorthwindEmployee


Friend Class NorthwindDataException
   Inherits Exception

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

End Namespace

Комментарии

ObjectDataSourceMethodEventArgs Класс используется в OnSelecting, OnUpdating, OnInserting, и OnDeleting методы для предоставления доступа к входные параметры, передаваемые Select, Update, Deleteи Insertметоды ObjectDataSource элемента управления.The ObjectDataSourceMethodEventArgs class is used in the OnSelecting, OnUpdating, OnInserting, and OnDeleting methods to provide access to input parameters that are passed to the Select, Update, Delete, and Insert methods of the ObjectDataSource control. Эти параметры осуществляется с помощью InputParameters свойство.These parameters are accessed using the InputParameters property. Путем добавления делегата для обработки Selecting, Updating, Inserting, или Deleting событий, можно проверить и обработки значений параметров и выполнения любой предварительной обработки, необходим.By adding a delegate to handle the Selecting, Updating, Inserting, or Deleting event, you can examine and manipulate the values of the parameters and perform any additional preprocessing that is required. Любые изменения параметров в этом словаре повлияет на какой метод перегрузка вызывается для операции.Any changes to the parameters in this dictionary will affect which method overload is called for the operation. Когда DataObjectTypeName свойство ObjectDataSource элемента управления задано значение, можно изменять только свойства объекта данных для элементов в словаре; нельзя добавить или удалить параметры.When the DataObjectTypeName property of the ObjectDataSource control is set, you can only modify the data object properties for the items in this dictionary; you cannot add or remove parameters. Дополнительные сведения см. в разделе Delete.For more information, see Delete.

ObjectDataSource Элемент управления предоставляет множество событий, которые можно обрабатывать для работы с базовой бизнес-объекта на различных этапах его жизненного цикла.The ObjectDataSource control exposes many events that you can handle to work with the underlying business object at various times in its life cycle. В следующей таблице перечислены события и связанные EventArgs классы и делегатов обработчиков событий.The following table lists the events and associated EventArgs classes and event handler delegates.

событиеEvent Класс EventArgsEventArgs class Делегата EventHandlerEventHandler delegate
ObjectCreating.ObjectCreating.

Происходит непосредственно перед создается экземпляр бизнес-объекта.Occurs immediately before the instance of the business object is created.
ObjectDataSourceEventArgs ObjectDataSourceObjectEventHandler
ObjectCreated.ObjectCreated.

Происходит непосредственно после создания экземпляра бизнес-объекта.Occurs immediately after the instance of the business object is created.
ObjectDataSourceEventArgs ObjectDataSourceObjectEventHandler
Selecting.Selecting.

Происходит до извлечения данных.Occurs before the data is retrieved.
ObjectDataSourceSelectingEventArgs ObjectDataSourceSelectingEventHandler
Inserting, Updating и Deleting.Inserting, Updating, and Deleting.

Возникает перед выполнением операции удаления, вставки или обновления.Occur before an insert, update, or delete operation is performed.
ObjectDataSourceMethodEventArgs ObjectDataSourceMethodEventHandler
Selected.Selected.

Происходит после получения данных.Occurs after the data is retrieved.
ObjectDataSourceStatusEventArgs ObjectDataSourceStatusEventHandler
Inserted, Updated и Deleted.Inserted, Updated, and Deleted.

Возникает после завершения вставки, обновления или операции удаления.Occur after the insert, update, or delete operation is completed.
ObjectDataSourceStatusEventArgs ObjectDataSourceStatusEventHandler
ObjectDisposing.ObjectDisposing.

Происходит перед уничтожением бизнес-объекта.Occurs before a business object is destroyed.
ObjectDataSourceDisposingEventArgs ObjectDataSourceDisposingEventHandler

Конструкторы

ObjectDataSourceMethodEventArgs(IOrderedDictionary) ObjectDataSourceMethodEventArgs(IOrderedDictionary) ObjectDataSourceMethodEventArgs(IOrderedDictionary) ObjectDataSourceMethodEventArgs(IOrderedDictionary)

Инициализирует новый экземпляр класса ObjectDataSourceMethodEventArgs, используя указанную коллекцию входных параметров.Initializes a new instance of the ObjectDataSourceMethodEventArgs class using the specified input parameters collection.

Свойства

Cancel Cancel Cancel Cancel

Возвращает или задает значение, показывающее, следует ли отменить событие.Gets or sets a value indicating whether the event should be canceled.

(Inherited from CancelEventArgs)
InputParameters InputParameters InputParameters InputParameters

Возвращает коллекцию, содержащую параметры метода бизнес-объекта и их значения.Gets a collection that contains business object method parameters and their values.

Методы

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Определяет, равен ли заданный объект текущему объекту.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Служит хэш-функцией по умолчанию.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Inherited from Object)

Применяется к

Дополнительно