Binding 類別

定義

表示物件屬性值和控制項屬性值之間的簡單繫結 (Simple Binding)。

public ref class Binding
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ListBindingConverter))]
public class Binding
[<System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.ListBindingConverter))>]
type Binding = class
Public Class Binding
繼承
Binding
屬性

範例

下列程式碼範例會建立 Windows Form,其中包含數個示範簡單資料系結的控制項。 此範例會建立具有兩個名為 DataSetCustomersOrders 的資料表,以及名為 custToOrdersDataRelation 。 四個控制項 (a 和三 TextBoxDateTimePicker 控制項) 系結至資料表中的資料行。 針對每個控制項,此範例會透過 DataBindings 屬性建立 並加入 Binding 至 控制項。 此範例會 BindingManagerBase 透過表單 的 傳回每個資料表的 BindingContext 。 四 Button 個控制項會 Position 遞增或遞減 物件上的 BindingManagerBase 屬性。

#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.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 ,在 控制項的 屬性與 物件的 屬性,或 物件清單中的目前 物件的 屬性之間建立和維護簡單的系結。

第一個案例的範例是,您可以將 控制項的 TextBox 屬性系結 TextFirstName 物件的 屬性 Customer 。 第二個案例的範例是,您可以將 控制項的 TextBox 屬性系結 TextFirstName 包含客戶的 屬性 DataTable

類別 Binding 也可讓您格式化值,以便透過 Format 事件顯示,以及透過 Parse 事件擷取格式化的值。

使用 Binding 建構函式建構 Binding 實例時,您必須指定三個專案:

  • 要系結的控制項屬性名稱。

  • 資料來源。

  • 解析為數據源中清單或屬性的流覽路徑。 流覽路徑也可用來建立物件的 BindingMemberInfo 屬性。

首先,您必須指定要系結資料的控制項屬性名稱。 例如,若要在 控制項中 TextBox 顯示資料,請指定 Text 屬性。

其次,您可以將下表中任一類別的實例指定為數據源。

描述 C# 範例
實作 IBindingListITypedList 的任何類別。 這些包括下列專案: DataSetDataTableDataViewDataViewManager DataSet ds = new DataSet("myDataSet");
實作 IList 以建立物件索引集合的任何類別。 必須先建立並填入集合, Binding 才能建立 。 清單中的物件必須全部是相同的類型;否則,將會擲回例外狀況。 ArrayList ar1 = new ArrayList; Customer1 cust1 = new Customer("Louis"); ar1.Add(cust1);
強型別物件的強型 IList Customer [] custList = new Customer[3];

第三,您必須指定導覽路徑,可以是空字串 (「」) 、單一屬性名稱或以句點分隔的名稱階層。 如果您將導覽路徑設定為空字串, ToString 則會在基礎資料來源物件上呼叫 方法。

如果資料來源是 DataTable ,它可以包含多個 DataColumn 物件,則必須使用導覽路徑來解析為特定資料行。

注意

當資料來源是 DataSetDataViewManagerDataTable 時,您實際上是系結至 DataView 。 因此,系結的資料列實際上是 DataRowView 物件。

當資料來源設定為包含多個 DataTable 物件的物件時,需要以句點分隔的導覽路徑 (,例如 DataSetDataViewManager) 。 當您系結至屬性傳回其他物件的物件時,您也可以使用句點分隔的導覽路徑,其屬性會傳回其他物件的參考 (例如具有傳回其他類別物件之屬性的類別) 。 例如,下列導覽路徑全都描述有效的資料欄位:

  • 「Size.Height」

  • 「Suppliers.CompanyName」

  • 「Regions.regionsToCustomers.CustomerFirstName」

  • 「Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity」

路徑的每個成員都可以傳回解析為單一值的屬性 (例如整數) ,或是 (值清單,例如字串陣列) 。 雖然路徑中的每個成員可以是清單或屬性,但最終成員必須解析為屬性。 每個成員建置在先前的成員上:「Size.Height」 會解析為 Height 目前 Size 的屬性;「Regions.regionsToCustomers.CustomerFirstName」 解析為目前客戶的名字,其中客戶是目前區域的其中一個客戶。

DataRelation 回值清單,方法是將一個 DataTable 連結至 中的第二 DataTableDataSetDataSet如果 包含 DataRelation 物件,您可以將資料成員指定為 TableName ,後面 RelationName 接著 ,然後指定 ColumnName 。 例如,如果 DataTable 具名的 「Suppliers」 包含 DataRelation 名為 「suppliers2products」 的 ,資料成員可能是 「Suppliers.suppliers2products.ProductName」。

資料來源可以包含一組相關的類別。 例如,假設有一組類別會編錄太陽能系統。 名為 System 的類別包含名為 Stars 的屬性,該屬性會傳回 物件的集合 Star 。 每個 Star 物件都有 NameMass 屬性,以及 Planets 傳回 物件集合的屬性 Planet 。 在此系統中,每個行星也有 MassName 屬性。 每個 Planet 物件都有一個 Moons 屬性,可傳回 物件的集合 Moon ,其中每個物件也有 NameMass 屬性。 如果您將 System 物件指定為數據源,您可以將下列任一專案指定為資料成員:

  • 「Stars.Name」

  • 「Stars.Mass」

  • 「Stars.Planets.Name」

  • 「Stars.Planets.Mass」

  • 「Stars.Planets.Moons.Name」

  • 「Stars.Planets.Moons.Mass」

可以是簡單系結的 Binding 控制項是 中的 ControlBindingsCollection 物件集合,您可以透過控制項的 DataBindings 屬性進行存取。 Binding您可以藉由呼叫 Add 方法,將 控制項的 屬性系結至物件的屬性, (或系結至清單中目前物件的 屬性) 。

您可以簡單系結至衍生自 System.Windows.Forms.Control 類別的任何物件,例如下列 Windows 控制項:

注意

SelectedValue只有 、 CheckedListBoxListBox 控制項的 ComboBox 屬性是簡單的系結。

類別 BindingManagerBase 是抽象類別,可管理特定資料來源和資料成員的所有 Binding 物件。 衍生自 BindingManagerBasePropertyManager 類別是 CurrencyManager 和 類別。 Binding管理的方式取決於 Binding 是清單系結還是屬性系結。 例如,如果是清單系結,您可以使用 在 BindingManagerBase 清單中指定 Position ; Position 因此,會決定清單中所有專案 (的專案) 實際上系結至控制項。 若要傳回適當的 BindingManagerBase ,請使用 BindingContext

若要將新資料列新增至系結至相同 DataSource 的控制項集,請使用 AddNew 類別的 BindingManagerBase 方法。 Item[]使用 類別的 BindingContext 屬性可傳回適當的 CurrencyManager 。 若要逸出新資料列的加入,請使用 CancelCurrentEdit 方法。

建構函式

Binding(String, Object, String)

初始化 Binding 類別的新執行個體,其可將所指的控制項屬性簡單繫結至資料來源的指定資料成員。

Binding(String, Object, String, Boolean)

初始化 Binding 類別的新執行個體,其可將表示的控制項屬性繫結至資料來源的指定資料成員,並選擇性地啟用要套用的格式。

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

初始化 Binding 類別的新執行個體,其可將指定的控制項屬性繫結至指定資料來源的指定資料成員。 選擇性地啟用格式,並根據指定的更新設定將值散佈至資料來源。

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

初始化 Binding 類別的新執行個體,其可將指定的控制項屬性繫結至指定之資料來源的指定資料成員。 選擇性地啟用格式、根據指定的更新設定將值散佈至資料來源,並當從資料來源傳回 DBNull 時將屬性設為指定的值。

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

初始化 Binding 類別的新執行個體,其可將指定的控制項屬性繫結至指定資料來源的指定資料成員。 選擇性地啟用包含指定格式字串的格式、根據指定的更新設定將值散佈至資料來源,並且在從資料來源傳回 DBNull 時將屬性設定為指定的值。

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

初始化 Binding 類別的新執行個體,其可將指定的控制項屬性繫結至指定資料來源的指定資料成員。 使用指定的格式字串選擇性地啟用格式;根據指定的更新設定將值散佈至資料來源;使用指定的格式字串啟用格式;當從資料來源傳回 DBNull 時將屬性設為指定的值,並設定指定的格式提供者。

屬性

BindableComponent

取得與 Binding 有關聯的控制項。

BindingManagerBase

取得此 BindingManagerBaseBinding

BindingMemberInfo

根據 Binding 建構函式中的 dataMember 參數,取得包含這個繫結之相關資訊的物件。

Control

取得繫結所屬的控制項。

ControlUpdateMode

取得或設定資料來源的變更何時送到已繫結的控制項屬性的值。

DataSource

取得這個繫結的資料來源。

DataSourceNullValue

如果控制項值為 null 或空白,則取得或設定要儲存在資料來源中的值。

DataSourceUpdateMode

取得或設定值,此值表示何時將繫結控制屬性填入到資料來源中。

FormatInfo

取得或設定提供自訂格式化行為的 IFormatProvider

FormatString

取得或設定格式規範字元,表示要如何顯示值。

FormattingEnabled

取得或設定值,指出控制項屬性資料是否會套用類型轉換和格式。

IsBinding

取得值,指出繫結是否在作用中。

NullValue

取得或設定當資料來源包含 Object 值時要設定成控制項屬性的 DBNull

PropertyName

取得控制項的資料繫結屬性名稱。

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnBindingComplete(BindingCompleteEventArgs)

引發 BindingComplete 事件。

OnFormat(ConvertEventArgs)

引發 Format 事件。

OnParse(ConvertEventArgs)

引發 Parse 事件。

ReadValue()

將控制項屬性設定為從資料來源讀取的值。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
WriteValue()

從控制項屬性讀取目前的值,並將它寫入資料來源中。

事件

BindingComplete

發生於 FormattingEnabled 屬性設定為 true 且繫結作業完成時,例如將資料從控制項推入資料來源時,反之亦然。

Format

發生於控制項屬性繫結至資料值時。

Parse

發生於資料繫結控制項的值變更時。

適用於

另請參閱