다음을 통해 공유


Binding 클래스

개체 속성 값과 컨트롤 속성 값 사이의 단순 바인딩을 나타냅니다.

네임스페이스: System.Windows.Forms
어셈블리: System.Windows.Forms(system.windows.forms.dll)

구문

‘선언
Public Class Binding
‘사용 방법
Dim instance As Binding
public class Binding
public ref class Binding
public class Binding
public class Binding

설명

Binding 클래스를 사용하여 컨트롤 속성과 개체 속성 사이의 단순 바인딩 및 컨트롤 속성과 개체 목록에 있는 현재 개체의 속성 사이의 단순 바인딩을 만들고 관리할 수 있습니다.

첫 번째 경우의 예로 TextBox 컨트롤의 Text 속성을 Customer 개체의 FirstName 속성에 바인딩할 수 있습니다. 또한 두 번째 경우의 예로 TextBox 컨트롤의 Text 속성을 Customer가 들어 있는 DataTableFirstName 속성에 바인딩할 수 있습니다.

또한 Binding클래스를 사용하면 Format 이벤트를 통해 형식을 지정하고, 형식이 지정된 값을 Parse이벤트를 사용하여 검색할 수도 있습니다.

Binding 생성자로 Binding 인스턴스를 생성할 때 다음 세 가지 항목을 지정해야 합니다.

  • 바인딩할 컨트롤 속성의 이름

  • 데이터 소스

  • 데이터 소스에 있는 속성이나 목록에 대한 탐색 경로. 탐색 경로는 해당 개체의 BindingMemberInfo 속성을 만드는 데도 사용됩니다.

우선, 데이터를 바인딩하려는 대상이 되는 컨트롤의 이름을 지정해야 합니다. 예를 들어, 해당 데이터를 TextBox 컨트롤에서 표시하려면 Text 속성을 지정해야 합니다.

그런 후 다음 표에 나열된 모든 클래스의 인스턴스를 데이터 소스로 지정할 수 있습니다.

설명

C# 예제

IBindingList 또는 ITypedList를 구현하는 모든 클래스. 이러한 클래스에는 DataSet, DataTable, DataView 또는 DataViewManager가 있습니다.

DataSet ds = new DataSet("myDataSet");

IList를 구현하여 개체의 인덱싱된 컬렉션을 만드는 클래스. Binding을 만들기 전에 컬렉션을 만들고 채워야 합니다. 목록에 있는 개체는 형식이 모두 같아야 합니다. 그렇지 않으면 예외가 throw됩니다.

ArrayList ar1 = new ArrayList;
Customer1 cust1 = new Customer("Louis");
ar1.Add(cust1);

강력한 형식의 개체로 구성된 강력한 형식의 IList

Customer [] custList = new Customer[3];

마지막으로, 빈 문자열(“”), 단일 속성 이름 또는 마침표로 분리된 속성 이름의 계층 구조를 사용하여 탐색 경로를 지정합니다. 탐색 경로를 빈 문자열로 설정하면 내부 데이터 소스 개체에 대해 ToString 메서드가 호출됩니다.

여러 개의 DataColumn 개체를 포함할 수 있는 DataTable이 데이터 소스인 경우, 탐색 경로는 특정 열로 연결되도록 지정해야 합니다.

참고

DataSet, DataViewManager 또는 DataTable이 데이터 소스이면 실제로는 DataView에 바인딩하는 것입니다. 결과적으로, 바인딩된 열은 실제적으로 DataRowView 개체입니다.

데이터 소스가 DataTable 여러 개가 포함된 개체가 들어 있는 개체(예: DataSet 또는 DataViewManager)로 설정된 경우에는 마침표로 분리된 탐색 경로를 사용해야 합니다. 마침표로 분리된 탐색 경로는 다른 클래스 개체를 반환하는 속성이 있는 클래스의 경우처럼, 해당 속성이 다른 개체에 대한 참조를 반환하는 개체에 바인딩하는 경우에도 사용할 수 있습니다. 예를 들어, 다음 탐색 경로는 모두 유효한 데이터 필드를 나타냅니다.

  • "Size.Height"

  • "Suppliers.CompanyName"

  • "Regions.regionsToCustomers.CustomerFirstName"

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

경로의 각 멤버는 값이 하나(예: 정수)만 포함된 속성 또는 여러 값의 목록(예: 문자열 배열)이 포함된 속성을 반환합니다. 목록이나 속성이 경로의 멤버가 될 수는 있지만 마지막 멤버는 반드시 속성이어야 합니다. 각 멤버는 이전 멤버를 바탕으로 하여 생성됩니다. "Size.Height"는 현재 Size에 대한 Height 속성으로 연결되며 "Regions.regionsToCustomers.CustomerFirstName"은 현재 지역(region)에 속한 고객(customer) 중 현재 고객의 이름(first name)으로 연결됩니다.

DataRelationDataTable 하나를 DataSet에 들어 있는 다른 DataTable에 연결하고 일련의 값 목록을 반환합니다. DataSetDataRelation 개체가 포함되어 있다면 데이터 멤버는 TableName, RelationName 그리고 ColumnName 순으로 지정할 수 있습니다. 예를 들어, 이름이 "Suppliers"인 DataTable에 이름이 "suppliers2products"인 DataRelation가 포함되어 있으면 데이터 멤버는 "Suppliers.suppliers2products.ProductName"처럼 지정합니다.

데이터 소스에는 관련된 클래스의 집합이 포함될 수 있습니다. 예를 들어, 태양계를 카탈로그화하는 클래스의 집합이 있다고 가정합니다. System 클래스에는 Star 개체의 컬렉션을 반환하는 Stars 속성이 들어 있습니다. 각 Star 개체에는 Planet 개체의 컬렉션을 반환하는 Planets 속성뿐만 아니라 NameMass 속성도 들어 있습니다. 또한 이 시스템에 속한 각 Planet에는 MassName 속성이 있습니다. 또한 각 Planet 개체에는 Moon 개체의 컬렉션을 반환하는 Moons 속성이 있으며 각 Moon 개체에도 NameMass 속성이 있습니다. System 개체를 데이터 소스로 지정하면 다음을 데이터 멤버로 지정할 수 있습니다.

  • "Stars.Name"

  • "Stars.Mass"

  • "Stars.Planets.Name"

  • "Stars.Planets.Mass"

  • "Stars.Planets.Moons.Name"

  • "Stars.Planets.Moons.Mass"

단순 바인딩될 수 있는 컨트롤은 ControlBindingsCollection 내에 들어 있는 Binding 개체의 컬렉션을 구성하며, 여기에는 해당 컨트롤의 DataBindings 속성을 통해 액세스할 수 있습니다. Add 메서드 호출로 컬렉션에 Binding을 추가하여 컨트롤의 속성을 개체의 속성에 바인딩하거나 목록에 있는 현재 개체의 속성에 바인딩합니다.

다음의 Windows 컨트롤처럼 System.Windows.Forms.Control 클래스에서 파생되는 개체는 모두 단순 바인딩할 수 있습니다.

참고

ComboBox, CheckedListBoxListBox 컨트롤의 경우에는 SelectedValue 속성만 단순 바인딩됩니다.

BindingManagerBase 클래스는 특정 데이터 소스와 데이터 멤버에 대해 모든 Binding 개체를 관리하는 추상 클래스입니다. BindingManagerBase에서 파생되는 클래스는 CurrencyManagerPropertyManager 클래스입니다. Binding을 관리하는 방식은 Binding이 목록 바인딩인지 또는 속성 바인딩인지에 따라 다릅니다. 예를 들어, 목록 바인딩인 경우 BindingManagerBase를 사용하여 목록에 Position을 지정할 수 있습니다. 즉, Position에 따라 목록의 모든 항목 중에서 실제로 컨트롤에 바인딩되는 항목이 결정됩니다. 적절한 BindingManagerBase를 반환하려면 BindingContext를 사용하십시오.

동일한 DataSource에 바인딩된 컨트롤의 집합에 새 행을 추가하려면 BindingManagerBase 클래스의 AddNew 메서드를 사용합니다. BindingContext 클래스의 Item 속성을 사용하여 적절한 CurrencyManager를 반환합니다. 새 행을 추가하는 작업을 중단하려면 CancelCurrentEdit 메서드를 사용합니다.

예제

다음 코드 예제에서는 단순 데이터 바인딩을 보여 주는 몇 가지 컨트롤을 사용하여 Windows Form을 만듭니다. 이 예제에서는 CustomersOrders 테이블과 custToOrders라는 이름의 DataRelation이 들어 있는 DataSet을 만듭니다. 폼에 있는 컨트롤 네 개(DateTimePicker 한 개와 TextBox 세 개)는 모두 테이블의 열에 데이터 바인딩되어 있습니다. 예제에서는 각 컨트롤에 대해 DataBindings 속성을 사용하여 Binding을 만들고 이를 컨트롤에 추가합니다. 예제에서는 폼의 BindingContext를 통해 각 테이블에 대한 BindingManagerBase를 반환합니다. 네 개의 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
         
         .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

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

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

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

   Private 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
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);
         }
      }
   }
 }
#using <system.dll>
#using <system.data.dll>
#using <system.drawing.dll>
#using <system.windows.forms.dll>
#using <system.xml.dll>

using namespace System;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Globalization;
using namespace System::Windows::Forms;

#define null 0L
public ref class Form1: public Form
{
private:
   System::ComponentModel::Container^ components;
   Button^ button1;
   Button^ button2;
   Button^ button3;
   Button^ button4;
   TextBox^ text1;
   TextBox^ text2;
   TextBox^ text3;
   BindingManagerBase^ bmCustomers;
   BindingManagerBase^ bmOrders;
   DataSet^ ds;
   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 = gcnew System::ComponentModel::Container;
      this->button1 = gcnew Button;
      this->button2 = gcnew Button;
      this->button3 = gcnew Button;
      this->button4 = gcnew Button;
      this->text1 = gcnew TextBox;
      this->text2 = gcnew TextBox;
      this->text3 = gcnew TextBox;
      this->DateTimePicker1 = gcnew DateTimePicker;
      this->Text =  "Binding Sample";
      this->ClientSize = System::Drawing::Size( 450, 200 );
      button1->Location = System::Drawing::Point( 24, 16 );
      button1->Size = System::Drawing::Size( 64, 24 );
      button1->Text =  "<";
      button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click );
      button2->Location = System::Drawing::Point( 90, 16 );
      button2->Size = System::Drawing::Size( 64, 24 );
      button2->Text =  ">";
      button2->Click += gcnew System::EventHandler( this, &Form1::button2_Click );
      button3->Location = System::Drawing::Point( 90, 100 );
      button3->Size = System::Drawing::Size( 64, 24 );
      button3->Text =  "<";
      button3->Click += gcnew System::EventHandler( this, &Form1::button3_Click );
      button4->Location = System::Drawing::Point( 150, 100 );
      button4->Size = System::Drawing::Size( 64, 24 );
      button4->Text =  ">";
      button4->Click += gcnew System::EventHandler( this, &Form1::button4_Click );
      text1->Location = System::Drawing::Point( 24, 50 );
      text1->Size = System::Drawing::Size( 150, 24 );
      text2->Location = System::Drawing::Point( 190, 50 );
      text2->Size = System::Drawing::Size( 150, 24 );
      text3->Location = System::Drawing::Point( 290, 150 );
      text3->Size = System::Drawing::Size( 150, 24 );
      DateTimePicker1->Location = System::Drawing::Point( 90, 150 );
      DateTimePicker1->Size = 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 );
   }

public:
   ~Form1()
   {
      if ( components != nullptr )
      {
         delete components;
      }
   }

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( gcnew Binding( "Text",ds,"customers.custName" ) );
      text2->DataBindings->Add( gcnew 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( gcnew 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 = gcnew Binding( "Text",ds,"customers.custToOrders.OrderAmount" );
      b->Parse += gcnew ConvertEventHandler( this, &Form1::CurrencyStringToDecimal );
      b->Format += gcnew ConvertEventHandler( this, &Form1::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 != String::typeid )
            return;

      cevent->Value = (dynamic_cast<Decimal^>(cevent->Value))->ToString( "c" );
   }

   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 != Decimal::typeid )
            return;

      cevent->Value = Decimal::Parse( cevent->Value->ToString(), NumberStyles::Currency, nullptr );
      
      /* 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;
   }

   void button2_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      // Go to the next item in the Customer list.
      bmCustomers->Position += 1;
   }

   void button3_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      
      // Go to the previous item in the Orders list.
      bmOrders->Position = bmOrders->Position - 1;
   }

   void button4_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      
      // Go to the next item in the Orders list.
      bmOrders->Position = bmOrders->Position + 1;
   }

private:

   // Create a DataSet with two tables and populate it.
   void MakeDataSet()
   {
      // Create a DataSet.
      ds = gcnew DataSet( "myDataSet" );

      // Create two DataTables.
      DataTable^ tCust = gcnew DataTable( "Customers" );
      DataTable^ tOrders = gcnew DataTable( "Orders" );

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

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

      DataRow^ newRow2; // = new DataRow();

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

      }
      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" ] = System::DateTime( 2001, i, j * 2 );
            newRow2[ "OrderAmount" ] = i * 10 + j * .1;
            
            // Add the row to the Orders table.
            tOrders->Rows->Add( newRow2 );
         }
      }
   }
};

int main()
{
   Application::Run( gcnew Form1 );
}
import System.*;
import System.Data.*;
import System.Drawing.*;
import System.Globalization.*;
import System.Windows.Forms.*;

public class Form1 extends 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();
    } //Form1

    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.set_Text("Binding Sample");
        this.set_ClientSize(new System.Drawing.Size(450, 200));
        button1.set_Location(new System.Drawing.Point(24, 16));
        button1.set_Size(new System.Drawing.Size(64, 24));
        button1.set_Text("<");
        button1.add_Click(new System.EventHandler(button1_Click));
        button2.set_Location(new System.Drawing.Point(90, 16));
        button2.set_Size(new System.Drawing.Size(64, 24));
        button2.set_Text(">");
        button2.add_Click(new System.EventHandler(button2_Click));
        button3.set_Location(new System.Drawing.Point(90, 100));
        button3.set_Size(new System.Drawing.Size(64, 24));
        button3.set_Text("<");
        button3.add_Click(new System.EventHandler(button3_Click));
        button4.set_Location(new System.Drawing.Point(150, 100));
        button4.set_Size(new System.Drawing.Size(64, 24));
        button4.set_Text(">");
        button4.add_Click(new System.EventHandler(button4_Click));
        text1.set_Location(new System.Drawing.Point(24, 50));
        text1.set_Size(new System.Drawing.Size(150, 24));
        text2.set_Location(new System.Drawing.Point(190, 50));
        text2.set_Size(new System.Drawing.Size(150, 24));
        text3.set_Location(new System.Drawing.Point(290, 150));
        text3.set_Size(new System.Drawing.Size(150, 24));
        dateTimePicker1.set_Location(new System.Drawing.Point(90, 150));
        dateTimePicker1.set_Size(new System.Drawing.Size(200, 800));
        this.get_Controls().Add(button1);
        this.get_Controls().Add(button2);
        this.get_Controls().Add(button3);
        this.get_Controls().Add(button4);
        this.get_Controls().Add(text1);
        this.get_Controls().Add(text2);
        this.get_Controls().Add(text3);
        this.get_Controls().Add(dateTimePicker1);
    } //InitializeComponent

    protected void Dispose(boolean disposing)
    {
        if (disposing) {
            if (components != null) {
                components.Dispose();
            }
        }
        super.Dispose(disposing);
    } //Dispose

    public static void main(String[] args)
    {
        Application.Run(new Form1());
    } //main

    private void SetUp()
    {
        // Create a DataSet with two tables and one relation.
        MakeDataSet();
        BindControls();
    } //SetUp

    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.get_DataBindings().Add(new Binding("Text", ds, 
            "customers.custName"));
        text2.get_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.get_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.add_Parse(new ConvertEventHandler(CurrencyStringToDecimal));
        b.add_Format(new ConvertEventHandler(DecimalToCurrencyString));
        text3.get_DataBindings().Add(b);

        // Get the BindingManagerBase for the Customers table. 
        bmCustomers = this.get_BindingContext().get_Item(ds, "Customers");

        /* Get the BindingManagerBase for the Orders table using the 
           RelationName. 
         */
        bmOrders = this.get_BindingContext().get_Item(ds, 
            "customers.CustToOrders");
    } //BindControls

    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.get_DesiredType().Equals(String.class.ToType())) {
            return;
        }
        cevent.set_Value(((System.Decimal)(cevent.get_Value())).ToString("c"));
    } //DecimalToCurrencyString

    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.get_DesiredType().Equals(System.Decimal.class.ToType())) {
            return;
        }
        cevent.set_Value(Decimal.Parse(cevent.get_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.get_Value());
    } //CurrencyStringToDecimal

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

    protected void button2_Click(Object sender, System.EventArgs e)
    {
        // Go to the next item in the Customer list.
        bmCustomers.set_Position(bmCustomers.get_Position() + 1);
    } //button2_Click

    protected void button3_Click(Object sender, System.EventArgs e)
    {
        // Go to the previous item in the Orders list.
        bmOrders.set_Position(bmOrders.get_Position() - 1);
    } //button3_Click

    protected void button4_Click(Object sender, System.EventArgs e)
    {
        // Go to the next item in the Orders list.
        bmOrders.set_Position(bmOrders.get_Position() + 1);
    } //button4_Click

    // 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", int.class.ToType());
        DataColumn cCustName = new DataColumn("CustName");

        tCust.get_Columns().Add(cCustID);
        tCust.get_Columns().Add(cCustName);

        // Create three columns, and add them to the second table.
        DataColumn cID = new DataColumn("CustID", int.class.ToType());
        DataColumn cOrderDate = new DataColumn("orderDate", 
            DateTime.class.ToType());
        DataColumn cOrderAmount = new DataColumn("OrderAmount", 
            System.Decimal.class.ToType());

        tOrders.get_Columns().Add(cOrderAmount);
        tOrders.get_Columns().Add(cID);
        tOrders.get_Columns().Add(cOrderDate);

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

        // Create a DataRelation, and add it to the DataSet.
        DataRelation dr = new DataRelation("custToOrders", cCustID, cID);
        ds.get_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.set_Item("custID", (Int32)i);
            // Add the row to the Customers table.
            tCust.get_Rows().Add(newRow1);
        }

        // Give each customer a distinct name.
        tCust.get_Rows().get_Item(0).set_Item("custName", "Alpha");
        tCust.get_Rows().get_Item(1).set_Item("custName", "Beta");
        tCust.get_Rows().get_Item(2).set_Item("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.set_Item("CustID", (Int32)i);
                newRow2.set_Item("orderDate", new DateTime(2001, i, j * 2));
                newRow2.set_Item("OrderAmount",    
                    (System.Double)(i * 10 + j * 0.1));
                // Add the row to the Orders table.
                tOrders.get_Rows().Add(newRow2);
            }
        }
    } //MakeDataSet
} //Form1
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.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.Object
  System.Windows.Forms.Binding

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Binding 멤버
System.Windows.Forms 네임스페이스
BindingContext
BindingManagerBase
ComboBox
DataGrid