Binding Binding Binding Binding Class

定義

オブジェクトのプロパティ値とコントロールのプロパティ値との間の簡易バインドを表します。Represents the simple binding between the property value of an object and the property value of a control.

public ref class Binding
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ListBindingConverter))]
public class Binding
type Binding = class
Public Class Binding
継承
BindingBindingBindingBinding
属性

次のコード例では、単純なデータ バインディングを示すいくつかのコントロールと Windows フォームを作成します。The following code example creates a Windows Form with several controls that demonstrate simple data binding. 例は、作成、DataSetという名前の 2 つのテーブルCustomersOrders、およびDataRelationという名前custToOrdersします。The example creates a DataSet with two tables named Customers and Orders, and a DataRelation named custToOrders. 4 つのコントロール (、DateTimePickerと 3 つTextBoxコントロール) のデータは、テーブル内の列にバインドされます。Four controls (a DateTimePicker and three TextBox controls) are data bound to columns in the tables. 各コントロールの例が作成し、追加、Bindingを通じてコントロールをDataBindingsプロパティ。For each control, the example creates and adds a Binding to the control through the DataBindings property. 例を返します、BindingManagerBaseフォームの各テーブルに対してBindingContextします。The example returns a BindingManagerBase for each table through the form's BindingContext. 次の 4 つButtonインクリメントまたはデクリメントの制御、PositionプロパティをBindingManagerBaseオブジェクト。Four Button controls increment or decrement the Position property on the BindingManagerBase objects.

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

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 (components IsNot 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 cevent.DesiredType IsNot 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 cevent.DesiredType IsNot 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

注釈

使用して、Bindingクラスを作成し、コントロールのプロパティと、オブジェクトのプロパティまたはオブジェクトの一覧の現在のオブジェクトのプロパティのいずれかの簡単なバインディングを維持します。Use the Binding class to create and maintain a simple binding between the property of a control and either the property of an object, or the property of the current object in a list of objects.

最初のケースの例は、としてバインドすることができます、TextのプロパティをTextBoxへの制御、FirstNameのプロパティをCustomerオブジェクト。As an example of the first case, you can bind the Text property of a TextBox control to the FirstName property of a Customer object. 2 番目のケースの例は、としてバインドすることができます、TextのプロパティをTextBoxコントロールをFirstNameのプロパティ、DataTable顧客を格納しています。As an example of the second case, you can bind the Text property of a TextBox control to the FirstName property of a DataTable that contains customers.

Bindingクラスでは値を表示するための書式設定することもできます、Formatイベントを書式設定された値を取得して、Parseイベント。The Binding class also enables you to format values for display through the Format event and to retrieve formatted values through the Parse event.

構築するときに、BindingインスタンスBindingコンス トラクターは、3 つの項目を指定する必要があります。When constructing a Binding instance with Binding constructor, you must specify three items:

  • バインドするコントロール プロパティの名前。The name of the control property to bind to.

  • データ ソース。The data source.

  • リストまたはデータ ソースのプロパティに解決されるナビゲーション パス。The navigation path that resolves to a list or property in the data source. ナビゲーション パスは、オブジェクトの作成にも使用BindingMemberInfoプロパティ。The navigation path is also used to create the object's BindingMemberInfo property.

まず、データをバインドするコントロール プロパティの名前を指定する必要があります。First, you must specify name of the control property you want to bind the data to. たとえば、データを表示する、TextBoxコントロールを指定、Textプロパティ。For example, to display data in a TextBox control, specify the Text property.

次に、データ ソースとして、次の表に、クラスのいずれかのインスタンスを指定できます。Second, you can specify an instance of any one of the classes in the following table as the data source.

説明Description C# の例C# example
実装するクラスIBindingListまたはITypedListします。Any class that implements IBindingList or ITypedList. 次が含まれます: DataSetDataTableDataView、またはDataViewManagerします。These include the following: DataSet, DataTable, DataView, or DataViewManager. DataSet ds = new DataSet("myDataSet");
実装するクラスIListインデックス付きオブジェクトのコレクションを作成します。Any class that implements IList to create an indexed collection of objects. コレクションを作成および作成する前に入力する必要があります、Bindingします。The collection must be created and filled before creating the Binding. 同じ型のリスト内のオブジェクトすべてする必要があります。それ以外の場合、例外がスローされます。The objects in the list must all be of the same type; otherwise, an exception will be thrown. ArrayList ar1 = new ArrayList; Customer1 cust1 = new Customer("Louis"); ar1.Add(cust1);
厳密に型指定されたIList厳密に型指定されたオブジェクトのA strongly typed IList of strongly typed objects Customer [] custList = new Customer[3];

3 番目に、空の文字列を指定することができますのナビゲーション パスを指定する必要があります ("")、1 つのプロパティ名、またはピリオド区切りの階層の名前。Third, you must specify the navigation path, which can be an empty string (""), a single property name, or a period-delimited hierarchy of names. ナビゲーション パスを空の文字列に設定した場合、ToString基になるデータ ソース オブジェクトでメソッドが呼び出されます。If you set the navigation path to an empty string, the ToString method will be called on the underlying data source object.

データ ソースがある場合、DataTableを複数含めることができるDataColumnオブジェクトの場合、特定の列に解決するのには、ナビゲーション パスを使用する必要があります。If the data source is a DataTable, which can contain multiple DataColumn objects, the navigation path must be used to resolve to a specific column.

注意

データ ソースの場合、 DataSetDataViewManager、またはDataTable、実際にバインドする、 DataViewWhen the data source is a DataSet, DataViewManager, or DataTable, you are actually binding to a DataView. そのため、バインドされている行が、実際にはDataRowViewオブジェクト。Consequently, the bound rows are actually DataRowView objects.

データ ソースが複数含まれるオブジェクトに設定されている場合、ピリオドで区切られたナビゲーション パスが必要なDataTableオブジェクト (など、DataSetまたはDataViewManager)。A period-delimited navigation path is required when the data source is set to an object that contains multiple DataTable objects (such as a DataSet or DataViewManager). (その他のクラス オブジェクトを返すプロパティを持つクラス) などの他のオブジェクトへの参照を返すプロパティを持つオブジェクトにバインドする場合は、ピリオド区切りのナビゲーション パスを使用することもできます。You can also use a period-delimited navigation path when you bind to an object whose properties return references to other objects (such as a class with properties that return other class objects). たとえば、次のすべてのナビゲーション パスでは、有効なデータ フィールドについて説明します。For example, the following navigation paths all describe valid data fields:

  • "Size.Height""Size.Height"

  • "Suppliers.CompanyName""Suppliers.CompanyName"

  • "Regions.regionsToCustomers.CustomerFirstName""Regions.regionsToCustomers.CustomerFirstName"

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

パスの各メンバーには、(整数) などの 1 つの値に解決されるプロパティまたは文字列の配列) などの値の一覧のいずれかを返すことができます。Each member of the path can return either a property that resolves to a single value (such as an integer), or a list of values (such as an array of strings). パス内の各メンバーは、リストまたはプロパティが、最後のメンバーがプロパティに解決する必要があります。Although each member in the path can be a list or property, the final member must resolve to a property. 各メンバーは、前のメンバーには。「1 つ」に解決、Heightプロパティ、現在のSize;"Regions.regionsToCustomers.CustomerFirstName"に解決されます名、現在の顧客の顧客が現在の地域の顧客のいずれか。Each member builds on the previous member: "Size.Height" resolves to the Height property for the current Size; "Regions.regionsToCustomers.CustomerFirstName" resolves to the first name for the current customer, where the customer is one of the customers for the current region.

A DataRelation 1 つをリンクすることによって値の一覧を返しますDataTableもう 1 つDataTableで、DataSetします。A DataRelation returns a list of values by linking one DataTable to a second DataTable in a DataSet. 場合、DataSetが含まれていますDataRelationオブジェクトとしてデータ メンバーを指定できます、TableName続けて、RelationNameをクリックし、ColumnNameします。If the DataSet contains DataRelation objects, you can specify the data member as a TableName followed by a RelationName, and then a ColumnName. たとえば場合、 DataTable "Suppliers"という名前が含まれています、 DataRelation "suppliers2products"という名前をデータ メンバーで"Suppliers.suppliers2products.ProductName"可能性があります。For example, if the DataTable named "Suppliers" contains a DataRelation named "suppliers2products", the data member could be "Suppliers.suppliers2products.ProductName".

データ ソースは、一連の関連するクラスで構成できます。The data source can consist of a set of related classes. たとえば、太陽系を一連のクラスがあるとします。For example, imagine a set of classes that catalogs solar systems. という名前のクラスSystemという名前のプロパティを含むStarsのコレクションを返すStarオブジェクト。The class named System contains a property named Stars that returns a collection of Star objects. StarオブジェクトがNameMassプロパティと同様に、Planetsプロパティのコレクションを返すPlanetオブジェクト。Each Star object has Name and Mass properties, as well as a Planets property that returns a collection of Planet objects. このシステムで各惑星もMassNameプロパティ。In this system, each planet also has Mass and Name properties. Planetオブジェクトをさらに、Moonsプロパティのコレクションを返すMoonがあり、いずれもオブジェクトNameMassプロパティ。Each Planet object further has a Moons property that returns a collection of Moon objects, each of which also has Name and Mass properties. 指定した場合、Systemデータ ソースとしてオブジェクトのデータ メンバーとして、次のいずれかを指定できます。If you specify a System object as the data source, you can specify any of the following as the data member:

  • "Stars.Name""Stars.Name"

  • "Stars.Mass""Stars.Mass"

  • "Stars.Planets.Name""Stars.Planets.Name"

  • "Stars.Planets.Mass""Stars.Planets.Mass"

  • "Stars.Planets.Moons.Name""Stars.Planets.Moons.Name"

  • "Stars.Planets.Moons.Mass""Stars.Planets.Moons.Mass"

単純バインド可能なコントロールの機能のコレクションBinding内のオブジェクトをControlBindingsCollection、コントロールのアクセスできるDataBindingsプロパティ。Controls that can be simple-bound feature a collection of Binding objects in a ControlBindingsCollection, which you can access through the control's DataBindings property. 追加する、Bindingを呼び出すことによってコレクションに、Addメソッド、オブジェクトのプロパティ (または一覧の現在のオブジェクトのプロパティ) これにより、コントロールのプロパティをバインドします。You add a Binding to the collection by calling the Add method, thereby binding a property of the control to a property of an object (or to a property of the current object in a list).

単純な連結できますから派生した任意のオブジェクトに、System.Windows.Forms.Controlクラス、たとえば、次の Windows コントロール。You can simple-bind to any object that derives from the System.Windows.Forms.Control class, for example, the following Windows controls:

注意

のみ、SelectedValueのプロパティ、 ComboBoxCheckedListBox、およびListBoxコントロールは、単純なバインドです。Only the SelectedValue property of the ComboBox, CheckedListBox, and ListBox control is simple bound.

BindingManagerBaseクラスはすべてを管理する抽象クラス、Binding特定のデータ ソースおよびデータ メンバーのオブジェクト。The BindingManagerBase class is an abstract class that manages all the Binding objects for a particular data source and data member. 派生するクラスBindingManagerBaseは、CurrencyManagerPropertyManagerクラス。Classes that derive from BindingManagerBase are the CurrencyManager and the PropertyManager classes. 方法、Bindingが管理されているかどうかによって異なります、Bindingがリストのバインディングまたはプロパティのバインディング。How a Binding is managed depends on whether the Binding is a list binding or a property binding. たとえば、リストのバインドの場合、使える、BindingManagerBaseを指定する、Positionの一覧で、 Position、したがって、決定 (外のすべての項目の一覧で) どの項目がコントロールにバインドが実際には。For example, if it is a list binding, you can use the BindingManagerBase to specify a Position in the list; the Position, therefore, determines which item (out of all items in the list) is actually bound to a control. 適切な戻りますBindingManagerBaseを使用して、BindingContextします。To return the appropriate BindingManagerBase, use the BindingContext.

コントロールに同じバインドのセットに新しい行を追加するDataSourceを使用して、AddNewのメソッド、BindingManagerBaseクラス。To add a new row to a set of controls bound to the same DataSource, use the AddNew method of the BindingManagerBase class. 使用して、Item[Object]のプロパティ、BindingContextを返す適切なクラスをCurrencyManagerします。Use the Item[Object] property of the BindingContext class to return the appropriate CurrencyManager. 新しい行の追加をエスケープするには使用、CancelCurrentEditメソッド。To escape the addition of the new row, use the CancelCurrentEdit method.

コンストラクター

Binding(String, Object, String) Binding(String, Object, String) Binding(String, Object, String) Binding(String, Object, String)

新しいインスタンスを初期化、Bindingクラスのデータ ソースの指定したデータ メンバーを指定したコントロール プロパティを単純なバインドです。Initializes a new instance of the Binding class that simple-binds the indicated control property to the specified data member of the data source.

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

新しいインスタンスを初期化、Bindingクラス、データ ソースの指定したデータ メンバーを指定したコントロール プロパティをバインドし、書式を適用するオプションで有効にします。Initializes a new instance of the Binding class that binds the indicated control property to the specified data member of the data source, and optionally enables formatting to be applied.

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

新しいインスタンスを初期化、Binding指定したデータ ソースの指定したデータ メンバーに指定したコントロール プロパティをバインドするクラス。Initializes a new instance of the Binding class that binds the specified control property to the specified data member of the specified data source. オプションで書式を有効にしたり、特定の更新設定に基づいてデータ ソースに値を反映したりできます。Optionally enables formatting and propagates values to the data source based on the specified update setting.

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

新しいインスタンスを初期化、Binding指定したデータ ソースの指定したデータ メンバーに指定したコントロール プロパティをバインドするクラス。Initializes a new instance of the Binding class that binds the indicated control property to the specified data member of the specified data source. 必要に応じて書式設定できるように、特定の更新設定に基づいてデータ ソースに値を反映およびを指定したプロパティを設定値と、DBNullがデータ ソースから返されます。Optionally enables formatting, propagates values to the data source based on the specified update setting, and sets the property to the specified value when a DBNull is returned from the data source.

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

新しいインスタンスを初期化、Binding指定したデータ ソースの指定したデータ メンバーに指定したコントロール プロパティをバインドするクラス。Initializes a new instance of the Binding class that binds the specified control property to the specified data member of the specified data source. 必要に応じて有効にされた、指定した書式指定文字列の書式設定指定した更新設定に基づいてデータ ソースに値を反映したり指定したプロパティを設定およびときの値をDBNullがデータ ソースから返されます。Optionally enables formatting with the specified format string; propagates values to the data source based on the specified update setting; and sets the property to the specified value when a DBNull is returned from the data source.

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

新しいインスタンスを初期化、Binding指定したデータ ソースの指定したデータ メンバーに指定したコントロール プロパティを持つクラス。Initializes a new instance of the Binding class with the specified control property to the specified data member of the specified data source. 必要に応じて有効にされた、指定した書式指定文字列の書式設定指定した更新設定に基づいてデータ ソースに値を反映したりにより、指定した書式指定文字列で書式設定指定したプロパティを設定するときの値をDBNull; データ ソースから返され、指定した書式プロバイダーを設定します。Optionally enables formatting with the specified format string; propagates values to the data source based on the specified update setting; enables formatting with the specified format string; sets the property to the specified value when a DBNull is returned from the data source; and sets the specified format provider.

プロパティ

BindableComponent BindableComponent BindableComponent BindableComponent

コントロールを取得、Bindingに関連付けられています。Gets the control the Binding is associated with.

BindingManagerBase BindingManagerBase BindingManagerBase BindingManagerBase

この BindingManagerBaseBinding を取得します。Gets the BindingManagerBase for this Binding.

BindingMemberInfo BindingMemberInfo BindingMemberInfo BindingMemberInfo

に基づいて、バインディングに関する情報を格納するオブジェクトを取得、dataMemberパラメーター、Bindingコンス トラクター。Gets an object that contains information about this binding based on the dataMember parameter in the Binding constructor.

Control Control Control Control

バインディングが属するコントロールを取得します。Gets the control that the binding belongs to.

ControlUpdateMode ControlUpdateMode ControlUpdateMode ControlUpdateMode

データ ソースの変更が、バインドされたコントロール プロパティにいつ反映されるかを取得または設定します。Gets or sets when changes to the data source are propagated to the bound control property.

DataSource DataSource DataSource DataSource

このバインディングのデータ ソースを取得します。Gets the data source for this binding.

DataSourceNullValue DataSourceNullValue DataSourceNullValue DataSourceNullValue

コントロールの値がある場合は、データ ソースに格納される値の設定を取得またはnullまたは空です。Gets or sets the value to be stored in the data source if the control value is null or empty.

DataSourceUpdateMode DataSourceUpdateMode DataSourceUpdateMode DataSourceUpdateMode

バインドされたコントロール プロパティの変更がデータ ソースにいつ反映されるかを示す値を取得または設定します。Gets or sets a value that indicates when changes to the bound control property are propagated to the data source.

FormatInfo FormatInfo FormatInfo FormatInfo

取得または設定します、IFormatProviderカスタム書式設定動作を提供します。Gets or sets the IFormatProvider that provides custom formatting behavior.

FormatString FormatString FormatString FormatString

値の表示方法を示す書式指定子文字を取得または設定します。Gets or sets the format specifier characters that indicate how a value is to be displayed.

FormattingEnabled FormattingEnabled FormattingEnabled FormattingEnabled

コントロール プロパティ データに型変換および書式指定が適用されるかどうかを示す値を取得または設定します。Gets or sets a value indicating whether type conversion and formatting is applied to the control property data.

IsBinding IsBinding IsBinding IsBinding

バインディングがアクティブかどうかを示す値を取得します。Gets a value indicating whether the binding is active.

NullValue NullValue NullValue NullValue

取得または設定します、Objectデータ ソースに含まれる場合に、コントロール プロパティとして設定される、DBNull値。Gets or sets the Object to be set as the control property when the data source contains a DBNull value.

PropertyName PropertyName PropertyName PropertyName

コントロールのデータ バインド プロパティの名前を取得します。Gets the name of the control's data-bound property.

メソッド

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

指定したオブジェクトが、現在のオブジェクトと等しいかどうかを判断します。Determines whether the specified object is equal to the current object.

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

既定のハッシュ関数として機能します。Serves as the default hash function.

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

現在のインスタンスの Type を取得します。Gets the Type of the current instance.

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

現在の Object の簡易コピーを作成します。Creates a shallow copy of the current Object.

(Inherited from Object)
OnBindingComplete(BindingCompleteEventArgs) OnBindingComplete(BindingCompleteEventArgs) OnBindingComplete(BindingCompleteEventArgs) OnBindingComplete(BindingCompleteEventArgs)

BindingComplete イベントを発生させます。Raises the BindingComplete event.

OnFormat(ConvertEventArgs) OnFormat(ConvertEventArgs) OnFormat(ConvertEventArgs) OnFormat(ConvertEventArgs)

Format イベントを発生させます。Raises the Format event.

OnParse(ConvertEventArgs) OnParse(ConvertEventArgs) OnParse(ConvertEventArgs) OnParse(ConvertEventArgs)

Parse イベントを発生させます。Raises the Parse event.

ReadValue() ReadValue() ReadValue() ReadValue()

コントロール プロパティをデータ ソースから読み取った値に設定します。Sets the control property to the value read from the data source.

ToString() ToString() ToString() ToString()

現在のオブジェクトを表す文字列を返します。Returns a string that represents the current object.

(Inherited from Object)
WriteValue() WriteValue() WriteValue() WriteValue()

コントロール プロパティから現在の値を読み取って、データ ソースに書き込みます。Reads the current value from the control property and writes it to the data source.

イベント

BindingComplete BindingComplete BindingComplete BindingComplete

発生したときに、FormattingEnabledプロパティに設定されてtrueバインディング操作が完了すると、データ ソースまたはその逆のコントロールからデータをプッシュする場合など、Occurs when the FormattingEnabled property is set to true and a binding operation is complete, such as when data is pushed from the control to the data source or vice versa

Format Format Format Format

コントロールのプロパティをデータ値にバインドすると発生します。Occurs when the property of a control is bound to a data value.

Parse Parse Parse Parse

データ連結コントロールの値が変更されると発生します。Occurs when the value of a data-bound control changes.

適用対象

こちらもご覧ください