次の方法で共有


Binding クラス

オブジェクトのプロパティ値とコントロールのプロパティ値との間の単純バインディングを表します。

この型のすべてのメンバの一覧については、Binding メンバ を参照してください。

System.Object
   System.Windows.Forms.Binding

Public Class Binding
[C#]
public class Binding
[C++]
public __gc class Binding
[JScript]
public class Binding

スレッドセーフ

この型の public static (Visual Basicでは Shared) のすべてのメンバは、マルチスレッド操作で安全に使用できます。インスタンスのメンバの場合は、スレッドセーフであるとは限りません。

解説

Binding クラスを使用して、オブジェクトのプロパティまたはオブジェクトのリスト内にある現在のオブジェクトのプロパティのいずれかと、コントロールのプロパティとの間に、単純バインディングを作成して維持します。

前者の例として、Customer オブジェクトの FirstName プロパティに、 TextBox コントロールの Text プロパティをバインドできます。後者の例として、顧客データを格納している DataTable の FirstName プロパティに、 TextBox コントロールの Text プロパティをバインドできます。

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

Binding コンストラクタを使用して Binding のインスタンスを構築する場合は、バインド先のコントロール プロパティの名前、データ ソース、およびリストまたはデータ ソース内のプロパティに解決されるナビゲーション パスの 3 つの項目を指定する必要があります。ナビゲーション パスは、オブジェクトの BindingMemberInfo を作成するときにも使用されます。

まず、データのバインド先とするコントロールのプロパティ名を指定する必要があります。たとえば、 TextBox コントロールにデータを表示するには、 Text プロパティを指定します。2 番目に、次のいずれかのクラスのインスタンスをデータ ソースとして指定できます。

説明
IBindingList または ITypedList を実装する任意のクラス。これらのクラスには、 DataSetDataTableDataViewDataViewManager などがあります。 C# の例:

DataSet ds = new DataSet("myDataSet");

IList を実装し、オブジェクトのインデックス付きコレクションを作成する任意のクラス。このコレクションは、 Binding オブジェクトを作成する前に作成され、その中にオブジェクトが格納されていることが必要です。リスト内のオブジェクトの型は、すべて同じである必要があります。それ以外の場合は、例外がスローされます。 C# の例:

ArrayList ar1 = new ArrayList;

Customer1 cust1 = new Customer("Louis");

ar1.Add(cust1);

厳密に型指定されたオブジェクトの、厳密に型指定された IList C# の例:

Customer [] custList = new Customer[3];

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

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

メモ   データ ソースが DataSetDataViewManager 、または DataTable の場合、実際には DataView にバインドされています。つまり、バインドされている行は、実際には DataRowView オブジェクトです。

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

  • "Size.Height"
  • "Suppliers.CompanyName"
  • "Regions.regionsToCustomers.CustomerFirstName"
  • "Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity"

パスの各メンバは、整数などの単一の値に解決されるプロパティ、または文字列配列などの値のリストを返す場合があります。パスの各メンバはリストまたはプロパティである可能性がありますが、最終メンバはプロパティに解決されることが必要です。各メンバは、1 つ前のメンバに基づいています。"Size.Height" は、現在の SizeHeight に解決されます。"Regions.regionsToCustomers.CustomerFirstName" は、現在の領域の顧客の 1 人である顧客の名前に解決されます。

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

データ ソースは、関連する一連のクラスで構成されます。たとえば、太陽系を形成する一連のクラスを想定します。System という名前のクラスは、star オブジェクトのコレクションを返す Stars という名前のプロパティを格納します。各 Star オブジェクトには、Name プロパティ、Mass プロパティ、および Planet オブジェクトのコレクションを返す Planets プロパティがあります。このシステムでは、各 planet にも Mass プロパティおよび Name プロパティがあります。さらに、各 Planet オブジェクトには、Moon オブジェクトのコレクションを返す 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 メソッドを呼び出します。これにより、コントロールのプロパティがオブジェクトのプロパティ、またはリスト内の現在のオブジェクトのプロパティにバインドされます。

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

メモ    ComboBoxCheckedListBoxListBox の各コントロールについては、 SelectedValue プロパティだけが単純バインドされます。

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

同じ DataSource にバインドされている一連のコントロールに新しい行を追加するには、 BindingManagerBase クラスの AddNew メソッドを使用します。適切な CurrencyManager を返すには、 BindingContext クラスの Item プロパティを使用します。新しい行の追加をキャンセルするには、 CancelCurrentEdit メソッドを使用します。

使用例

単純データ連結を行うコントロールがいくつか配置されている Windows フォームの作成例を次に示します。この例では、 Customers および Orders という名前の 2 つのテーブルを持つ DataSet と、 custToOrders という名前の DataRelation を作成します。4 つのコントロール (1 つの DateTimePicker コントロールと 3 つの TextBox コントロール) は、テーブル内の列にデータ連結されています。この例は、各コントロールに対して Binding を作成し、それぞれのコントロールに DataBindings プロパティを通じて追加します。また、フォームの BindingContext オブジェクトを通じて、各テーブルの BindingManagerBase オブジェクトを返します。4 つの Button コントロールが、 BindingManagerBase オブジェクトの Position プロパティをインクリメントまたはデクリメントします。

 
Imports System
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Globalization
Imports System.Windows.Forms

Public Class Form1
   Inherits Form

   Private components As Container
   Private button1 As Button
   Private button2 As Button
   Private button3 As Button
   Private button4 As Button
   Private text1 As TextBox
   Private text2 As TextBox
   Private text3 As TextBox

   Private bmCustomers As BindingManagerBase
   Private bmOrders As BindingManagerBase
   Private ds As DataSet
   Private DateTimePicker1 As DateTimePicker
   
   Public Sub New
      ' Required for Windows Form Designer support.
      InitializeComponent
      ' Call SetUp to bind the controls.
      SetUp
   End Sub

   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
    End Sub


   Private Sub InitializeComponent
      ' Create the form and its controls.
      With Me
         .components = New Container
         .button1 = New Button
         .button2 = New Button
         .button3 = New Button
         .button4 = New Button
         .text1 = New TextBox
         .text2 = New TextBox
         .text3 = New TextBox

         .DateTimePicker1 = New DateTimePicker
         
         .AutoScaleBaseSize = New Size(5, 13)
         .Text = "Binding Sample"
         .ClientSize = New Size(450, 200)

         With .button1
            .Location = New Point(24, 16)
            .Size = New Size(64, 24)
            .Text = "<"
            AddHandler button1.click, AddressOf button1_Click
         End With
         
         
         With .button2
            .Location = New Point(90, 16)
            .Size = New Size(64, 24)
            .Text = ">"
            AddHandler button2.click, AddressOf button2_Click
         End With
         
         With .button3
            .Location = New Point(90, 100)
            .Size = New Size(64, 24)
            .Text = ">"
            AddHandler button3.click, AddressOf button3_Click
         End With

         With .button4
            .Location = New Point(150, 100)
            .Size = New Size(64, 24)
            .Text = ">"
            AddHandler button4.click, AddressOf button4_Click
         End With

         With .text1
            .Location = New Point(24, 50)
            .Size = New Size(150, 24)
         End With

         With .text2
            .Location = New Point(190, 50)
            .Size = New Size(150, 24)
         End With

         With .text3
            .Location = New Point(290, 150)
            .Size = New Size(150, 24)
         End With

            With .DateTimePicker1
               .Location = New Point(90, 150)
               .Size = New Size(200, 800)
            End With

            With .Controls
            .Add(button1)
            .Add(button2)
            .Add(button3)
            .Add(button4)
            .Add(text1)
            .Add(text2)
            .Add(text3)
            .Add(DateTimePicker1)
            End With
      End With
   End Sub
      
   Public Shared Sub Main
      Application.Run(new Form1)
   End Sub

   Private Sub SetUp
      ' Create a DataSet with two tables and one relation.
      MakeDataSet
      BindControls
   End Sub

   Private Sub 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.
      Dim b As Binding = New _
         Binding("Text", ds, "customers.custToOrders.OrderAmount")
      AddHandler b.Parse, AddressOf CurrencyStringToDecimal
      AddHandler b.Format, AddressOf DecimalToCurrencyString
      text3.DataBindings.Add(b)
      
         ' Get the BindingManagerBase for the Customers table.
         bmCustomers = Me.BindingContext(ds, "Customers")

         ' Get the BindingManagerBase for the Orders table using the
         ' RelationName.
         bmOrders = Me.BindingContext(ds, "customers.CustToOrders")
   End Sub

   Private Sub DecimalToCurrencyString(sender As Object, cevent As ConvertEventArgs)
      ' 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 Not cevent.DesiredType Is GetType(String) Then
         Exit Sub
      End If 
   
      cevent.Value = CType(cevent.Value, decimal).ToString("c")
   End Sub

   Private Sub CurrencyStringToDecimal(sender As Object, cevent As ConvertEventArgs)
      ' 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 Not cevent.DesiredType Is GetType(decimal) Then
         Exit Sub
      End If

      cevent.Value = Decimal.Parse(cevent.Value.ToString, _
      NumberStyles.Currency, nothing)
      
      ' 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)
   End Sub

   Protected Sub button1_Click(sender As Object, e As System.EventArgs)
      ' Go to the previous item in the Customer list.
      bmCustomers.Position -= 1
   End Sub

   Protected Sub button2_Click(sender As Object, e As System.EventArgs)
      ' Go to the next item in the Customer list.
      bmCustomers.Position += 1
   End Sub

   Protected Sub button3_Click(sender As Object, e As System.EventArgs)
      ' Go to the previous item in the Order list.
      bmOrders.Position -= 1
   End Sub

   Protected Sub button4_Click(sender As Object, e As System.EventArgs)
      ' Go to the next item in the Orders list.
      bmOrders.Position += 1
   End Sub

   ' Creates a DataSet with two tables and populates it.
   Private Sub MakeDataSet
      ' Create a DataSet.
      ds = New DataSet("myDataSet")

      ' Creates two DataTables.
      Dim tCust As DataTable = New DataTable("Customers")
      Dim tOrders As DataTable = New DataTable("Orders")

      ' Create two columns, and add them to the first table.
      Dim cCustID As DataColumn = New DataColumn("CustID", _
      System.Type.GetType("System.Int32"))
      Dim cCustName As DataColumn = New DataColumn("CustName")
      tCust.Columns.Add(cCustID)
      tCust.Columns.Add(cCustName)

      ' Create three columns, and add them to the second table.
      Dim cID As DataColumn = _
         New DataColumn("CustID", System.Type.GetType("System.Int32"))
      Dim cOrderDate As DataColumn = _
         New DataColumn("orderDate", System.Type.GetType("System.DateTime"))
      Dim cOrderAmount As DataColumn = _
         New DataColumn("OrderAmount", System.Type.GetType("System.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.
      Dim dr As DataRelation = New _
         DataRelation("custToOrders", cCustID, cID)
      ds.Relations.Add(dr)
      
      ' Populate the tables. For each customer and orders,
      ' create two DataRow variables.
      Dim newRow1 As DataRow
      Dim newRow2 As DataRow

         ' Create three customers in the Customers Table.
         Dim i As Integer
         For i = 1 to 3
            newRow1 = tCust.NewRow
            newRow1("custID") = i
            ' Adds the row to the Customers table.
            tCust.Rows.Add(newRow1)
         Next

         ' 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.
         Dim j As Integer
         For i = 1 to 3
         For j = 1 to 5
            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)
         Next
         Next
   End Sub
End Class

[C#] 
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.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      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);
   }

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

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

   protected 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);
         }
      }
   }
 }


[C++] 
[JScript] 
import System;
import System.Data;
import System.Drawing;
import System.Globalization;
import System.Windows.Forms;

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

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

   public function Form1()
   {
      // Required for Windows Form Designer support.
      InitializeComponent();
      // Call SetUp to bind the controls.
      SetUp();
   }
 
   private function 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.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      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.add_Click(button1_Click);

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

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

      button4.Location = new System.Drawing.Point(150, 100);
      button4.Size = new System.Drawing.Size(64, 24);
      button4.Text = ">";
      button4.add_Click(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 function Dispose(disposing : boolean){
      if( disposing ){
         if (components != null){
            components.Dispose();}
      }
      super.Dispose( disposing );
   }

   public static function Main()
   {
      Application.Run(new Form1());
   }
   
   private function SetUp()
   {
      // Create a DataSet with two tables and one relation.
      MakeDataSet();
      BindControls();
   }

   protected function 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. */
      var b : Binding = new Binding
         ("Text", ds, "customers.custToOrders.OrderAmount");
      b.add_Parse(CurrencyStringToDecimal);
      b.add_Format(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 function DecimalToCurrencyString(sender, cevent : ConvertEventArgs)
   {
      /* 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 != String.GetType()) return;

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

   private function CurrencyStringToDecimal(sender, cevent : ConvertEventArgs)
   {   
      /* 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 != Decimal.GetType()) 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);
   }

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

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

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

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

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

      // Create three columns, and add them to the second table.
      var cID : DataColumn  = 
         new DataColumn("CustID", Int32);
      var cOrderDate : DataColumn  = 
         new DataColumn("orderDate", DateTime);
      var cOrderAmount : DataColumn = 
         new DataColumn("OrderAmount", 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.
      var dr : DataRelation = new DataRelation
      ("custToOrders", cCustID , cID);
      ds.Relations.Add(dr);
   
      /* Populate the tables. For each customer and order, 
         create two DataRow variables. */
      var newRow1 : DataRow;
      var newRow2 : DataRow;

      // Create three customers in the Customers Table.
      for(var i : int = 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(var j : int = 1; j < 4; j++)
      {
         for(var k : int = 1; k < 6; k++)
         {
            newRow2 = tOrders.NewRow();
            newRow2["CustID"]= j;
            newRow2["orderDate"]= new DateTime(2001, j, k * 2);
            newRow2["OrderAmount"] = j * 10 + k  * .1;
            // Add the row to the Orders table.
            tOrders.Rows.Add(newRow2);
         }
      }
   }
 }

必要条件

名前空間: System.Windows.Forms

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

アセンブリ: System.Windows.Forms (System.Windows.Forms.dll 内)

参照

Binding メンバ | System.Windows.Forms 名前空間 | BindingContext | BindingManagerBase | ComboBox | DataGrid