英語で読む

次の方法で共有


ObjectDataSourceMethodEventHandler 代理人

定義

Selecting コントロールの UpdatingInsertingDeletingObjectDataSource の各イベントを処理するメソッドを表します。

C#
public delegate void ObjectDataSourceMethodEventHandler(object sender, ObjectDataSourceMethodEventArgs e);

パラメーター

sender
Object

イベントのソースである ObjectDataSource

e
ObjectDataSourceMethodEventArgs

イベント データを格納している ObjectDataSourceMethodEventArgs

このセクションには、2 つのコード例が含まれています。 最初のコード例では、ビジネス オブジェクトとコントロールでコントロールを ObjectDataSource 使用してデータを DetailsView 挿入する方法を示します。 2 番目のコード例では、最初のコード例で使用される中間層ビジネス オブジェクトの例を示します。

次のコード例では、ビジネス オブジェクトとコントロールでコントロールを ObjectDataSource 使用してデータを DetailsView 挿入する方法を示します。 最初は、DetailsView自動的に生成された [挿入] ボタンと共に、新しいNorthwindEmployeeレコードが表示されます。 コントロールの DetailsView フィールドにデータを入力した後、[ 挿入 ] ボタンをクリックすると、アクションを InsertMethod 実行 Insert するメソッドがプロパティによって識別されます。

この例では、 メソッドを UpdateEmployeeInfo 使用して挿入を実行しますが、データを NorthwindEmployee 挿入するには パラメーターが必要です。 このため、コントロールが自動的に渡す DetailsView 文字列のコレクションでは十分ではありません。 デリゲートは NorthwindEmployeeInserting 、イベントを ObjectDataSourceMethodEventHandler 処理 Inserting するオブジェクトであり、操作を続行する前に入力パラメーターを Insert 操作できます。 メソッドには UpdateEmployeeInfo パラメーターとして オブジェクトが NorthwindEmployee 必要であるため、1 つは文字列のコレクションを使用して作成され、コレクションに InputParameters 追加されます。

ASP.NET (C#)
<%@ 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>

次のコード例では、前のコード例で使用する中間層ビジネス オブジェクトの例を示します。 このコード例は、次の 2 つの基本クラスと 1 つの追加クラスで構成されています。

  • クラス。 EmployeeLogic これは、ビジネス ロジックをカプセル化するステートレス クラスです。

  • クラス。 NorthwindEmployee これは、データ層からデータを読み込んで保持するために必要な基本的な機能のみを含むモデル クラスです。

  • 便利として提供される追加 NorthwindDataException のクラス。

この一連のクラス例は、Northwind Traders データベースで動作します。これは、Microsoft SQL Server と Microsoft Access で使用できるデータベースの例です。 完全な作業例として、これらのクラスを使用するには、これらのクラスをアプリケーション ルートの下のApp_Code ディレクトリに配置するか、ライブラリにコンパイルして、結果の DLL を Bin ディレクトリに配置します。 UpdateEmployeeInfoメソッドは完全には実装されていないため、この例を試しても Northwind Traders データベースにデータを挿入しません。

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

      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) { }
  }
}

注釈

コントロールの Selecting、、、または Deleting イベントを使用すると、コントロールによって呼び出されるメソッドを決定するために使用されるパラメーターをObjectDataSource操作できます。 InsertingUpdatingObjectDataSource 詳細については、「ObjectDataSourceMethodEventArgs」を参照してください。

ObjectDataSourceMethodEventHandler デリゲートを作成する場合は、イベントを処理するメソッドを指定します。 イベント ハンドラーにイベントを関連付けるには、イベントにデリゲートのインスタンスを追加します。 イベント ハンドラーは、デリゲートを削除しない限り、イベントが発生するたびに呼び出されます。 イベントを処理する方法の詳細については、次を参照してください。処理とイベントの発生します。

拡張メソッド

GetMethodInfo(Delegate)

指定したデリゲートによって表されるメソッドを表すオブジェクトを取得します。

適用対象

製品 バージョン
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

こちらもご覧ください