英語で読む

次の方法で共有


Binding クラス

定義

オブジェクトのプロパティ値とコントロールのプロパティ値との間の簡易バインドを表します。

[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ListBindingConverter))]
public class Binding
継承
Binding
属性

次のコード例では、単純なデータ バインディングを示す複数のコントロールを含む Windows フォームを作成します。 この例では、 DataSet と という名前の 2 つのテーブルとOrders、 というCustomers名前custToOrdersの を持つ をDataRelation作成します。 4 つのコントロール (および DateTimePicker 3 つの TextBox コントロール) は、テーブル内の列にバインドされたデータです。 この例では、各コントロールについて、 プロパティを Binding 使用して を作成し、コントロールに DataBindings を追加します。 この例では、フォームの を BindingManagerBase 介して各テーブルの BindingContextを返します。 4 つのButtonコントロールは、 オブジェクトの プロパティBindingManagerBasePositionインクリメントまたはデクリメントします。

using System;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
   private System.ComponentModel.Container components;
   private Button button1;
   private Button button2;
   private Button button3;
   private Button button4;
   private TextBox text1;
   private TextBox text2;
   private TextBox text3;

   private BindingManagerBase bmCustomers;
   private BindingManagerBase bmOrders;
   private DataSet ds;
   private DateTimePicker DateTimePicker1;

   public Form1()
   {
      // Required for Windows Form Designer support.
      InitializeComponent();
      // Call SetUp to bind the controls.
      SetUp();
   }
 
   private void InitializeComponent()
   {
      // Create the form and its controls.
      this.components = new System.ComponentModel.Container();
      this.button1 = new System.Windows.Forms.Button();
      this.button2 = new System.Windows.Forms.Button();
      this.button3 = new System.Windows.Forms.Button();
      this.button4 = new System.Windows.Forms.Button();
      
      this.text1= new System.Windows.Forms.TextBox();
      this.text2= new System.Windows.Forms.TextBox();
      this.text3= new System.Windows.Forms.TextBox();
      
      this.DateTimePicker1 = new DateTimePicker();
      
      this.Text = "Binding Sample";
      this.ClientSize = new System.Drawing.Size(450, 200);
      
      button1.Location = new System.Drawing.Point(24, 16);
      button1.Size = new System.Drawing.Size(64, 24);
      button1.Text = "<";
      button1.Click+=new System.EventHandler(button1_Click);

      button2.Location = new System.Drawing.Point(90, 16);
      button2.Size = new System.Drawing.Size(64, 24);
      button2.Text = ">";
      button2.Click+=new System.EventHandler(button2_Click);

      button3.Location = new System.Drawing.Point(90, 100);
      button3.Size = new System.Drawing.Size(64, 24);
      button3.Text = "<";
      button3.Click+=new System.EventHandler(button3_Click);

      button4.Location = new System.Drawing.Point(150, 100);
      button4.Size = new System.Drawing.Size(64, 24);
      button4.Text = ">";
      button4.Click+=new System.EventHandler(button4_Click);

      text1.Location = new System.Drawing.Point(24, 50);
      text1.Size = new System.Drawing.Size(150, 24);

      text2.Location = new System.Drawing.Point(190, 50);
      text2.Size = new System.Drawing.Size(150, 24);

      text3.Location = new System.Drawing.Point(290, 150);
      text3.Size = new System.Drawing.Size(150, 24);
      
      DateTimePicker1.Location = new System.Drawing.Point(90, 150);
      DateTimePicker1.Size = new System.Drawing.Size(200, 800);
      
      this.Controls.Add(button1);
      this.Controls.Add(button2);
      this.Controls.Add(button3);
      this.Controls.Add(button4);
      this.Controls.Add(text1);
      this.Controls.Add(text2);
      this.Controls.Add(text3);
      this.Controls.Add(DateTimePicker1);
   }

   protected override void Dispose( bool disposing ){
      if( disposing ){
         if (components != null){
            components.Dispose();}
      }
      base.Dispose( disposing );
   }
   public static void Main()
   {
      Application.Run(new Form1());
   }
   
   private void SetUp()
   {
      // Create a DataSet with two tables and one relation.
      MakeDataSet();
      BindControls();
   }

   protected void BindControls()
   {
      /* Create two Binding objects for the first two TextBox 
         controls. The data-bound property for both controls 
         is the Text property. The data source is a DataSet 
         (ds). The data member is the  
         "TableName.ColumnName" string. */
      text1.DataBindings.Add(new Binding
      ("Text", ds, "customers.custName"));
      text2.DataBindings.Add(new Binding
      ("Text", ds, "customers.custID"));
      
      /* Bind the DateTimePicker control by adding a new Binding. 
         The data member of the DateTimePicker is a 
         TableName.RelationName.ColumnName string. */
      DateTimePicker1.DataBindings.Add(new 
      Binding("Value", ds, "customers.CustToOrders.OrderDate"));

      /* Add event delegates for the Parse and Format events to a 
         new Binding object, and add the object to the third 
         TextBox control's BindingsCollection. The delegates 
         must be added before adding the Binding to the 
         collection; otherwise, no formatting occurs until 
         the Current object of the BindingManagerBase for 
         the data source changes. */
      Binding b = new Binding
         ("Text", ds, "customers.custToOrders.OrderAmount");
      b.Parse+=new ConvertEventHandler(CurrencyStringToDecimal);
      b.Format+=new ConvertEventHandler(DecimalToCurrencyString);
      text3.DataBindings.Add(b);

      // Get the BindingManagerBase for the Customers table. 
      bmCustomers = this.BindingContext [ds, "Customers"];

      /* Get the BindingManagerBase for the Orders table using the 
         RelationName. */ 
      bmOrders = this.BindingContext[ds, "customers.CustToOrders"];
   }

   private void DecimalToCurrencyString(object sender, ConvertEventArgs cevent)
   {
      /* This method is the Format event handler. Whenever the 
         control displays a new value, the value is converted from 
         its native Decimal type to a string. The ToString method 
         then formats the value as a Currency, by using the 
         formatting character "c". */

      // The application can only convert to string type. 
      if(cevent.DesiredType != typeof(string)) return;

      cevent.Value = ((decimal) cevent.Value).ToString("c");
   }

   private void CurrencyStringToDecimal(object sender, ConvertEventArgs cevent)
   {   
      /* This method is the Parse event handler. The Parse event 
         occurs whenever the displayed value changes. The static 
         ToDecimal method of the Convert class converts the 
         value back to its native Decimal type. */

      // Can only convert to decimal type.
      if(cevent.DesiredType != typeof(decimal)) return;

      cevent.Value = Decimal.Parse(cevent.Value.ToString(),
        NumberStyles.Currency, null);

      /* To see that no precision is lost, print the unformatted 
         value. For example, changing a value to "10.0001" 
         causes the control to display "10.00", but the 
         unformatted value remains "10.0001". */
      Console.WriteLine(cevent.Value);
   }

   private void button1_Click(object sender, System.EventArgs e)
   {
      // Go to the previous item in the Customer list.
      bmCustomers.Position -= 1;
   }

   private void button2_Click(object sender, System.EventArgs e)
   {
      // Go to the next item in the Customer list.
      bmCustomers.Position += 1;
   }
    
   private void button3_Click(object sender, System.EventArgs e)
   {
      // Go to the previous item in the Orders list.
      bmOrders.Position-=1;
   }

   private void button4_Click(object sender, System.EventArgs e)
   {
      // Go to the next item in the Orders list.
      bmOrders.Position+=1;
   }

   // Create a DataSet with two tables and populate it.
   private void MakeDataSet()
   {
      // Create a DataSet.
      ds = new DataSet("myDataSet");
      
      // Create two DataTables.
      DataTable tCust = new DataTable("Customers");
      DataTable tOrders = new DataTable("Orders");

      // Create two columns, and add them to the first table.
      DataColumn cCustID = new DataColumn("CustID", typeof(int));
      DataColumn cCustName = new DataColumn("CustName");
      tCust.Columns.Add(cCustID);
      tCust.Columns.Add(cCustName);

      // Create three columns, and add them to the second table.
      DataColumn cID = 
         new DataColumn("CustID", typeof(int));
      DataColumn cOrderDate = 
         new DataColumn("orderDate",typeof(DateTime));
      DataColumn cOrderAmount = 
         new DataColumn("OrderAmount", typeof(decimal));
      tOrders.Columns.Add(cOrderAmount);
      tOrders.Columns.Add(cID);
      tOrders.Columns.Add(cOrderDate);

      // Add the tables to the DataSet.
      ds.Tables.Add(tCust);
      ds.Tables.Add(tOrders);

      // Create a DataRelation, and add it to the DataSet.
      DataRelation dr = new DataRelation
      ("custToOrders", cCustID , cID);
      ds.Relations.Add(dr);
   
      /* Populate the tables. For each customer and order, 
         create two DataRow variables. */
      DataRow newRow1;
      DataRow newRow2;

      // Create three customers in the Customers Table.
      for(int i = 1; i < 4; i++)
      {
         newRow1 = tCust.NewRow();
         newRow1["custID"] = i;
         // Add the row to the Customers table.
         tCust.Rows.Add(newRow1);
      }
      // Give each customer a distinct name.
      tCust.Rows[0]["custName"] = "Alpha";
      tCust.Rows[1]["custName"] = "Beta";
      tCust.Rows[2]["custName"] = "Omega";
      
      // For each customer, create five rows in the Orders table.
      for(int i = 1; i < 4; i++)
      {
         for(int j = 1; j < 6; j++)
         {
            newRow2 = tOrders.NewRow();
            newRow2["CustID"]= i;
            newRow2["orderDate"]= new DateTime(2001, i, j * 2);
            newRow2["OrderAmount"] = i * 10 + j  * .1;
            // Add the row to the Orders table.
            tOrders.Rows.Add(newRow2);
         }
      }
   }
 }

注釈

クラスを Binding 使用して、コントロールの プロパティとオブジェクトの プロパティ、またはオブジェクトのリスト内の現在のオブジェクトの プロパティの間の単純なバインドを作成および維持します。

最初のケースの例として、コントロールの プロパティを TextTextBox オブジェクトの Customer プロパティにFirstNameバインドできます。 2 番目のケースの例として、顧客を Text 含む のプロパティ TextBoxFirstName コントロールの プロパティを DataTable バインドできます。

Bindingクラスを使用すると、イベントを通じて表示する値をFormat書式設定したり、イベントを通じて書式設定された値をParse取得したりすることもできます。

コンストラクターを使用BindingしてインスタンスをBinding構築する場合は、次の 3 つの項目を指定する必要があります。

  • バインドするコントロール プロパティの名前。

  • データ ソース。

  • データ ソース内のリストまたはプロパティに解決されるナビゲーション パス。 ナビゲーション パスは、オブジェクトの BindingMemberInfo プロパティを作成するためにも使用されます。

まず、データをバインドするコントロール プロパティの名前を指定する必要があります。 たとえば、コントロールにデータを TextBox 表示するには、 プロパティを Text 指定します。

次に、次の表のいずれかのクラスのインスタンスをデータ ソースとして指定できます。

[説明] C# の例
または ITypedListを実装するIBindingListクラス。 これには、、DataSetDataTableDataViewまたは DataViewManagerが含まれます。 DataSet ds = new DataSet("myDataSet");
オブジェクトの IList インデックス付きコレクションを作成するために を実装するクラス。 を作成する前に、コレクションを作成して入力する Binding必要があります。 リスト内のオブジェクトはすべて同じ型である必要があります。それ以外の場合は、例外がスローされます。 ArrayList ar1 = new ArrayList; Customer1 cust1 = new Customer("Louis"); ar1.Add(cust1);
厳密に型指定された IList オブジェクトの厳密に型指定されたオブジェクト Customer [] custList = new Customer[3];

3 つ目は、ナビゲーション パスを指定する必要があります。ナビゲーション パスには、空の文字列 ("")、単一のプロパティ名、またはピリオドで区切られた名前の階層を指定できます。 ナビゲーション パスを空の文字列に設定すると、 ToString 基になるデータ ソース オブジェクトで メソッドが呼び出されます。

データ ソースが である場合、 DataTable複数 DataColumn のオブジェクトを含めることができる場合は、ナビゲーション パスを使用して特定の列に解決する必要があります。

注意

データ ソースが 、DataViewManager、または DataTableDataSet場合、実際には にDataViewバインドされます。 したがって、バインドされた行は実際には DataRowView オブジェクトです。

データ ソースが複数DataTableのオブジェクト (や DataViewManagerなど) を含むオブジェクトに設定されている場合は、ピリオド区切りのナビゲーション パスがDataSet必要です。 また、ピリオド区切りのナビゲーション パスは、プロパティが他のオブジェクトへの参照を返すオブジェクト (他のクラス オブジェクトを返すプロパティを持つクラスなど) にバインドするときにも使用できます。 たとえば、次のナビゲーション パスはすべて、有効なデータ フィールドを記述します。

  • "Size.Height"

  • "Suppliers.CompanyName"

  • "Regions.regionsToCustomers.CustomerFirstName"

  • "Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity"

パスの各メンバーは、1 つの値 (整数など) に解決されるプロパティ、または値のリスト (文字列の配列など) を返すことができます。 パス内の各メンバーはリストまたはプロパティにすることができますが、最終的なメンバーは プロパティに解決する必要があります。 各メンバーは、前のメンバーに基づいてビルドされます。 "Size.Height" は現在SizeHeight の プロパティに解決されます。"Regions.regionsToCustomers.CustomerFirstName" は、現在の顧客の名に解決されます。ここで、顧客は現在のリージョンの顧客の 1 つです。

DataRelation 1 つを 1 DataTable 秒にリンクすることで、値の一覧をDataSet返しますDataTable。 に DataSet オブジェクトが DataRelation 含まれている場合は、 として TableName データ メンバーを指定し、その後に RelationNameを続けて を ColumnName指定できます。 たとえば、"Suppliers" という名前の DataTable に "suppliers2products" という名前が含まれている DataRelation 場合、データ メンバーは "Suppliers.suppliers2products.ProductName" になります。

データ ソースは、関連するクラスのセットで構成できます。 たとえば、太陽系をカタログ化するクラスのセットを想像してみてください。 という名前 System のクラスには、 オブジェクトのコレクションを返す という名前 StarsStar プロパティが含まれています。 各StarオブジェクトにはName、 プロパティと Mass プロパティ、および オブジェクトのPlanetコレクションをPlanets返す プロパティがあります。 このシステムでは、各惑星にも Mass および Name プロパティがあります。 各 Planet オブジェクトには Moons 、オブジェクトの Moon コレクションを返す プロパティがあります。各オブジェクトには Name および Mass プロパティもあります。 オブジェクトを System データ ソースとして指定する場合は、データ メンバーとして次のいずれかを指定できます。

  • "Stars.Name"

  • "Stars.Mass"

  • "Stars.Planets.Name"

  • "Stars.Planets.Mass"

  • "Stars.Planets.Moons.Name"

  • "Stars.Planets.Moons.Mass"

単純バインドできるコントロールは、 内ControlBindingsCollectionのオブジェクトのBindingコレクションを特徴とします。このコレクションには、コントロールの DataBindings プロパティを介してアクセスできます。 をコレクションに追加 Binding するには、 メソッドを Add 呼び出して、コントロールのプロパティをオブジェクトのプロパティ (またはリスト内の現在のオブジェクトのプロパティ) にバインドします。

クラスから System.Windows.Forms.Control 派生した任意のオブジェクト (たとえば、次の Windows コントロール) に単純にバインドできます。

注意

、、SelectedValueおよび ListBox コントロールの ComboBoxCheckedListBoxプロパティのみが単純にバインドされます。

クラスは BindingManagerBase 、特定のデータ ソースとデータ メンバーのすべての Binding オブジェクトを管理する抽象クラスです。 から BindingManagerBase 派生するクラスは、 CurrencyManager クラスと クラスです PropertyManager 。 の Binding 管理方法は、 がリスト バインドかプロパティ バインドか Binding によって異なります。 たとえば、リスト バインドの場合は、 を使用 BindingManagerBase してリストで を Position 指定できます。したがって、 は、(リスト Position内のすべてのアイテムから) 実際にコントロールにバインドされる項目を決定します。 適切な BindingManagerBaseを返すには、 を使用します BindingContext

同じ DataSourceにバインドされたコントロールのセットに新しい行を追加するには、 クラスの メソッドをAddNewBindingManagerBase使用します。 適切な を Item[] 返すには、 BindingContext クラスの プロパティを使用します CurrencyManager。 新しい行の追加をエスケープするには、 メソッドを使用します CancelCurrentEdit

コンストラクター

Binding(String, Object, String)

データ ソースの指定したデータ メンバーに、指定したコントロール プロパティを単純バインドする、Binding クラスの新しいインスタンスを初期化します。

Binding(String, Object, String, Boolean)

データ ソースの指定したデータ メンバーに、指定したコントロール プロパティをバインドし、オプションで書式設定を適用できるようにする、Binding クラスの新しいインスタンスを初期化します。

Binding(String, Object, String, Boolean, DataSourceUpdateMode)

指定したデータ ソースの指定したデータ メンバーに、指定したコントロール プロパティをバインドする、Binding クラスの新しいインスタンスを初期化します。 オプションで書式を有効にしたり、特定の更新設定に基づいてデータ ソースに値を反映したりできます。

Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object)

指定したデータ ソースの指定したデータ メンバーに、指定したコントロール プロパティをバインドする Binding クラスの新しいインスタンスを初期化します。 オプションで書式を有効にしたり、特定の更新設定に基づいてデータ ソースに値を反映したりできる以外に、データ ソースから DBNull が返された場合に使用されるプロパティ値を指定することもできます。

Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object, String)

指定したデータ ソースの指定したデータ メンバーに、指定したコントロール プロパティをバインドする、Binding クラスの新しいインスタンスを初期化します。 オプションとして、指定した書式指定文字列を含む書式を有効にしたり、指定した更新設定に基づいてデータ ソースに値を反映したりできます。また、DBNull がデータ ソースから返された場合に、指定した値をプロパティに設定することもできます。

Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object, String, IFormatProvider)

指定したデータ ソースの指定したデータ メンバーに、指定したコントロール プロパティをバインドする、Binding クラスの新しいインスタンスを初期化します。 オプションで、指定した書式指定文字列で書式を有効にしたり、特定の更新設定に基づいてデータ ソースに値を反映したりできる以外に、データ ソースから DBNull が返された場合に使用されるプロパティ値を指定したり、書式プロバイダーを指定することもできます。

プロパティ

BindableComponent

Binding が関連付けられているコントロールを取得します。

BindingManagerBase

この BindingManagerBaseBinding を取得します。

BindingMemberInfo

Binding コンストラクターの dataMember パラメーターに基づいて、バインディングに関する情報を格納しているオブジェクトを取得します。

Control

バインディングが属するコントロールを取得します。

ControlUpdateMode

データ ソースの変更が、バインドされたコントロール プロパティにいつ反映されるかを取得または設定します。

DataSource

このバインディングのデータ ソースを取得します。

DataSourceNullValue

コントロールの値が null または空の場合にデータ ソースに格納される値を取得または設定します。

DataSourceUpdateMode

バインドされたコントロール プロパティの変更がデータ ソースにいつ反映されるかを示す値を取得または設定します。

FormatInfo

カスタムの書式設定動作を定義する IFormatProvider を取得または設定します。

FormatString

値の表示方法を示す書式指定子文字を取得または設定します。

FormattingEnabled

コントロール プロパティ データに型変換および書式指定が適用されるかどうかを示す値を取得または設定します。

IsBinding

バインディングがアクティブかどうかを示す値を取得します。

NullValue

データ ソースに Object 値が格納されている場合にコントロール プロパティとして設定される DBNull を取得または設定します。

PropertyName

コントロールのデータ バインドされたプロパティの名前を取得します。

メソッド

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
OnBindingComplete(BindingCompleteEventArgs)

BindingComplete イベントを発生させます。

OnFormat(ConvertEventArgs)

Format イベントを発生させます。

OnParse(ConvertEventArgs)

Parse イベントを発生させます。

ReadValue()

コントロール プロパティをデータ ソースから読み取った値に設定します。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)
WriteValue()

コントロール プロパティから現在の値を読み取って、データ ソースに書き込みます。

イベント

BindingComplete

データがコントロールからデータ ソースにプッシュされた場合、またはその逆の場合などに、FormattingEnabled プロパティが true に設定され、バインディング操作が完了したときに発生します。

Format

コントロールのプロパティをデータ値にバインドすると発生します。

Parse

データ連結コントロールの値が変更されると発生します。

適用対象

製品 バージョン
.NET Framework 1.1, 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
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

こちらもご覧ください