Binding 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
代表某对象属性值和某控件属性值之间的简单绑定。
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 窗体,其中包含多个用于演示简单数据绑定的控件。 该示例创建一个 DataSet ,其中包含两个名为 Customers
和 Orders
的表,以及一个名为 DataRelation 的 custToOrders
。 (的四个控件和三TextBox个DateTimePicker控件) 绑定到表中的列的数据。 对于每个控件,该示例通过 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# 示例 |
---|---|
实现 IBindingList 或 ITypedList的任何类。 其中包括: DataSet、 DataTable、 DataView或 DataViewManager。 | DataSet ds = new DataSet("myDataSet"); |
实现 IList 以创建对象的索引集合的任何类。 在创建 之前 Binding,必须创建并填充集合。 列表中的对象必须全部属于同一类型;否则,将引发异常。 | ArrayList ar1 = new ArrayList; Customer1 cust1 = new Customer("Louis"); ar1.Add(cust1); |
强类型 IList 对象的强类型化 | Customer [] custList = new Customer[3]; |
第三,必须指定导航路径,该路径可以是空字符串 (“”) 、单个属性名称或以句点分隔的名称层次结构。 如果将导航路径设置为空字符串, ToString 则将对基础数据源对象调用 方法。
如果数据源是可以 DataTable包含多个 DataColumn 对象的 ,则必须使用导航路径解析为特定列。
备注
当数据源为 DataSet、 DataViewManager或 DataTable时,实际上是绑定到 。DataView 因此,绑定行实际上是 DataRowView 对象。
当数据源设置为包含多个DataTable对象 ((如 或 DataViewManager) )的对象时,DataSet需要句点分隔的导航路径。 当您绑定到属性返回对其他对象的引用的对象时,还可以使用句点分隔的导航路径 (例如具有返回) 其他类对象的属性的类。 例如,以下导航路径都描述了有效的数据字段:
“Size.Height”
“Suppliers.CompanyName”
“Regions.regionsToCustomers.CustomerFirstName”
“Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity”
路径的每个成员都可以返回解析为单个值的属性 ((如整数) )或 (值列表(如) 字符串数组)。 尽管路径中的每个成员都可以是列表或属性,但最终成员必须解析为属性。 每个成员都基于上一个成员生成:“Size.Height”解析为 Height 当前 Size的 属性;“Regions.regionsToCustomers.CustomerFirstName”解析为当前客户的名字,其中客户是当前区域的客户之一。
DataRelation通过将一个DataTable值链接到 中的DataSet第二DataTable个值,返回值列表。 DataSet如果 包含 DataRelation 对象,则可以将数据成员指定为 ,TableName后跟 RelationName,然后指定 。ColumnName 例如,如果 DataTable 名为“Suppliers”的 包含名为 DataRelation “suppliers2products”,则数据成员可以是“Suppliers.suppliers2products.ProductName”。
数据源可以包含一组相关类。 例如,假设有一组分类太阳系的类。 名为 的 System
类包含一个名为 Stars
的属性,该属性返回 对象的集合 Star
。 每个 Star
对象都具有 Name
和 Mass
属性,以及 Planets
返回 对象集合的属性 Planet
。 在这个系统中,每个行星也有 Mass
和 Name
属性。 此外,每个 Planet
对象都有一个 Moons
属性,该属性返回对象的集合 Moon
,其中每个对象还具有 Name
和 Mass
属性。 如果将对象指定为数据源,则可以将以下任一 System
项指定为数据成员:
“Stars.Name”
“Stars.Mass”
“Stars.Planets.Name”
“Stars.Planets.Mass”
“Stars.Planets.Moons.Name”
“Stars.Planets.Moons.Mass”
可简单绑定的控件具有 中的 ControlBindingsCollection对象的集合Binding,可以通过 控件的 DataBindings 属性访问这些对象。 通过调用 Add 方法将 添加到Binding集合中,从而将 控件的 属性绑定到 对象的属性 (或列表中当前对象的属性) 。
你可以简单绑定到派生自 System.Windows.Forms.Control 类的任何对象,例如,以下 Windows 控件:
注意
SelectedValue只有 、 CheckedListBox和 ListBox 控件的 ComboBox属性是简单绑定的。
类 BindingManagerBase 是一个抽象类,用于管理特定数据源和数据成员的所有 Binding 对象。 派生自 BindingManagerBase 的类是 CurrencyManager 和 PropertyManager 类。 Binding如何管理 取决于 是列表绑定还是Binding属性绑定。 例如,如果它是列表绑定,则可以使用 BindingManagerBase 在列表中指定 ;PositionPosition因此, 确定) 实际绑定到控件的列表中所有项 (哪个项。 若要返回相应的 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 |
获取此 BindingManagerBase 的 Binding。 |
BindingMemberInfo |
获取包含有关该绑定的信息的对象(基于 Binding 构造函数中的 |
Control |
获取绑定所属的控件。 |
ControlUpdateMode |
获取或设置将数据源的更改传播到绑定控件属性的时间。 |
DataSource |
获取该绑定的数据源。 |
DataSourceNullValue |
获取或设置将存储在数据源中的值(如果控件值为 |
DataSourceUpdateMode |
获取或设置一个值,该值指示将绑定控件属性的更改传播到数据源的时间。 |
FormatInfo |
获取或设置提供自定义格式设置行为的 IFormatProvider。 |
FormatString |
获取或设置指示如何显示值的格式说明符。 |
FormattingEnabled |
获取或设置一个值,该值指示是否对控件属性数据应用类型转换和格式设置。 |
IsBinding |
获取指示绑定是否活动的值。 |
NullValue | |
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 属性设置为 |
Format |
当将某控件的属性绑定到某个数据值时发生。 |
Parse |
在数据绑定控件的值更改时发生。 |