Binding Osztály
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Egy objektum tulajdonságértéke és egy vezérlőelem tulajdonságértéke közötti egyszerű kötést jelöli.
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
- Öröklődés
-
Binding
- Attribútumok
Példák
Az alábbi példakód egy Windows űrlapot hoz létre, amely számos olyan vezérlővel rendelkezik, amelyek egyszerű adatkötést mutatnak be. A példa létrehoz egy DataSet két táblát és CustomersOrdersegy elnevezett táblát DataRelationcustToOrders. Négy vezérlő (a DateTimePicker és három TextBox vezérlő) a táblák oszlopaihoz kötött adat. A példa minden vezérlőelemhez létrehoz és hozzáad egy Binding vezérlőt a DataBindings tulajdonságon keresztül. A példa egy-egy BindingManagerBase táblát ad vissza az űrlapon BindingContextkeresztül. Négy Button vezérlő növeli vagy lassítja az Position objektumok tulajdonságát 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
Megjegyzések
Binding Az osztály használatával egyszerű kötést hozhat létre és tarthat fenn egy vezérlőelem tulajdonsága és egy objektum tulajdonsága, vagy az aktuális objektum tulajdonsága között az objektumok listájában.
Az első eset példájaként egy vezérlőelem Text tulajdonságát TextBox egy objektum tulajdonságához FirstName köthetiCustomer. A második eset példájaként egy vezérlőelem tulajdonságát Text az ügyfeleket tartalmazó tulajdonsághoz TextBoxFirstName köthetiDataTable.
Az Binding osztály lehetővé teszi az értékek formázását az Format eseményen keresztüli megjelenítéshez és a formázott értékek beolvasásához az Parse eseményen keresztül.
Ha egy Binding példányt konstruktorral Binding hoz létre, három elemet kell megadnia:
Annak a vezérlőtulajdonságnak a neve, amelyhez csatlakozni szeretne.
Az adatforrás.
Az adatforrás egy listájára vagy tulajdonságára feloldó navigációs útvonal. A navigációs útvonal az objektum tulajdonságának BindingMemberInfo létrehozásához is használható.
Először meg kell adnia annak a vezérlőtulajdonságnak a nevét, amelyhez az adatokat hozzá szeretné kötni. Ha például egy TextBox vezérlőben szeretne adatokat megjeleníteni, adja meg a tulajdonságot Text .
Másodszor, adatforrásként az alábbi táblázat bármelyik osztályának egy példányát megadhatja.
| Leírás | C# példa |
|---|---|
| Bármely olyan osztály, amely implementálja IBindingList vagy ITypedList. Ezek közé tartoznak a következők: DataSet, DataTable, DataViewvagy DataViewManager. | DataSet ds = new DataSet("myDataSet"); |
| Minden olyan osztály, amely az objektumok indexelt gyűjteményének létrehozására implementál IList . A gyűjteményt a létrehozás előtt létre kell hozni és ki kell tölteni.Binding A listában szereplő objektumoknak azonos típusúnak kell lenniük; ellenkező esetben a rendszer kivételt fog kivenni. | ArrayList ar1 = new ArrayList; Customer1 cust1 = new Customer("Louis"); ar1.Add(cust1); |
| Erősen gépelt IList objektumok erősen gépelt objektumai | Customer [] custList = new Customer[3]; |
Harmadszor meg kell adnia a navigációs útvonalat, amely lehet üres sztring (""), egyetlen tulajdonságnév vagy a nevek ponthatárolt hierarchiája. Ha a navigációs útvonalat üres sztringre állítja, a ToString metódust a rendszer meghívja a mögöttes adatforrás-objektumon.
Ha az adatforrás egy DataTable, amely több DataColumn objektumot is tartalmazhat, a navigációs útvonalat egy adott oszlopra kell feloldani.
Note
Ha az adatforrás egy DataSet, DataViewManagervagy DataTable, akkor valójában egy DataView. Következésképpen a kötött sorok valójában DataRowView objektumok.
Ponthatárolt navigációs útvonalra van szükség, ha az adatforrás olyan objektumra van beállítva, amely több DataTable objektumot (például egy DataSet vagy DataViewManager) tartalmaz. Ponthatárolt navigációs útvonalat is használhat, ha olyan objektumhoz köt, amelynek tulajdonságai más objektumokra mutató hivatkozásokat ad vissza (például olyan osztályt, amely más osztályobjektumokat ad vissza). Az alábbi navigációs útvonalak például az érvényes adatmezőket írják le:
"Méret.Magasság"
"Suppliers.CompanyName"
"Regions.regionsToCustomers.CustomerFirstName"
"Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity"
Az elérési út minden tagja visszaadhat egy tulajdonságot, amely egyetlen értékre (például egész számra) vagy értéklistára (például sztringtömbre) oldódik fel. Bár az elérési út minden tagja lehet lista vagy tulajdonság, a végleges tagnak fel kell oldania egy tulajdonságot. Minden tag az előző tagra épít: "Méret.Magasság" feloldja az Height aktuális Size; A "Regions.regionsToCustomers.CustomerFirstName" az aktuális ügyfél utónevét oldja fel, ahol az ügyfél az aktuális régió egyik ügyfele.
A DataRelation függvény egy értéklistát ad vissza úgy, hogy az egyiket DataTable egy másodperchez DataTable csatolja egy DataSet. Ha a DataSet program objektumokat tartalmaz DataRelation , megadhatja az adattagot TableNameRelationNameegy , majd egy ColumnName. Ha például a DataTable "Szállítók" név egy "suppliers2products" nevű terméket tartalmaz DataRelation , az adattag lehet "Suppliers.suppliers2products.ProductName".
Az adatforrás több kapcsolódó osztályból állhat. Képzeljen el például egy olyan osztálycsoportot, amely naprendszereket katalogizál. A névvel ellátott System osztály egy objektumgyűjteményt Stars visszaadó tulajdonságot Star tartalmaz. Minden Star objektum rendelkezik Name és Mass rendelkezik tulajdonságokkal, valamint egy Planets olyan tulajdonsággal, amely egy objektumgyűjteményt Planet ad vissza. Ebben a rendszerben minden bolygó rendelkezik és Mass tulajdonságokkal is rendelkezikName. Minden Planet objektum rendelkezik egy Moons tulajdonsággal, amely egy objektumgyűjteményt Moon ad vissza, amelyek mindegyike rendelkezik és Name tulajdonságokkal is rendelkezikMass. Ha adatforrásként egy objektumot System ad meg, az alábbiak bármelyikét megadhatja adatelemként:
"Stars.Name"
"Stars.Mass"
"Stars.Planets.Name"
"Stars.Planets.Mass"
"Stars.Planets.Moons.Name"
"Stars.Planets.Moons.Mass"
Az egyszerű kötésű vezérlők objektumgyűjteményt BindingControlBindingsCollectionis tartalmazhatnak, amelyeket a vezérlő tulajdonságán DataBindings keresztül érhet el. A metódus meghívásával Binding hozzáadhat egy Add gyűjteményt, így a vezérlőelem tulajdonságát egy objektum (vagy egy lista aktuális objektumának egy tulajdonságához) köti.
Az System.Windows.Forms.Control osztályból származó objektumokhoz egyszerűen kapcsolódhat, például a következő Windows vezérlőelemekhez:
Note
Csak a SelectedValue , ComboBoxés CheckedListBox a ListBoxvezérlőelem tulajdonsága kötött.
Az BindingManagerBase osztály egy absztrakt osztály, amely egy adott adatforrás és adattag összes Binding objektumát kezeli. A származtatott BindingManagerBase osztályok az CurrencyManager osztályok és az PropertyManager osztályok. A Binding kezelés módjától függ, hogy listakötésről Binding vagy tulajdonságkötésről van-e szó. Ha például egy listakötésről van szó, BindingManagerBase a listában megadhat egy Position elemet, ezért a Positionlistában szereplő elemek közül a vezérlőelemhez kötött elemeket határozza meg. A megfelelő BindingManagerBasevisszaadásához használja a következőt BindingContext: .
Ha új sort szeretne hozzáadni egy azonoshoz DataSourcekötött vezérlőelem-készlethez, használja az AddNewBindingManagerBase osztály metódusát. Item[] Az osztály tulajdonságával BindingContext adja vissza a megfelelőtCurrencyManager. Az új sor hozzáadásának feloldásához használja a metódust CancelCurrentEdit .
Konstruktorok
| Name | Description |
|---|---|
| Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object, String, IFormatProvider) |
Inicializálja az Binding osztály új példányát a megadott vezérlőtulajdonság használatával a megadott adatforrás megadott adattagjára. Opcionálisan engedélyezi a megadott formázási sztringdel való formázást; a megadott frissítési beállítás alapján propagálja az értékeket az adatforrásba; engedélyezi a formázást a megadott formátumsztringgel; a tulajdonságot a megadott értékre állítja, amikor az adatforrásból ad vissza egy DBNull értéket, és beállítja a megadott formátumszolgáltatót. |
| Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object, String) |
Inicializálja annak az osztálynak az Binding új példányát, amely a megadott vezérlőtulajdonságot a megadott adatforrás megadott adateleméhez köti. Opcionálisan engedélyezi a megadott formázási sztringdel való formázást; a megadott frissítési beállítás alapján propagálja az értékeket az adatforrásba; és beállítja a tulajdonságot a megadott értékre, amikor az adatforrásból ad vissza egy DBNull értéket. |
| Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object) |
Inicializálja annak az osztálynak az Binding új példányát, amely a megadott vezérlőtulajdonságot a megadott adatforrás megadott adateleméhez köti. Opcionálisan engedélyezi a formázást, propagálja az értékeket az adatforrásba a megadott frissítési beállítás alapján, és a tulajdonságot a megadott értékre állítja, amikor az adatforrásból visszaad egy DBNull értéket. |
| Binding(String, Object, String, Boolean, DataSourceUpdateMode) |
Inicializálja annak az osztálynak az Binding új példányát, amely a megadott vezérlőtulajdonságot a megadott adatforrás megadott adateleméhez köti. Opcionálisan engedélyezi a formázást, és a megadott frissítési beállítás alapján propagálja az értékeket az adatforrásba. |
| Binding(String, Object, String, Boolean) |
Inicializálja az Binding osztály új példányát, amely a megadott vezérlőtulajdonságot az adatforrás megadott adateleméhez köti, és opcionálisan lehetővé teszi a formázás alkalmazását. |
| Binding(String, Object, String) |
Inicializálja az Binding osztály új példányát, amely egyszerű kötéssel köti a megadott vezérlőtulajdonságot az adatforrás megadott adateleméhez. |
Tulajdonságok
| Name | Description |
|---|---|
| BindableComponent |
Lekéri azt a vezérlőt, Binding amelyhez társítva van. |
| BindingManagerBase |
Megkapja ezt BindingManagerBasea Binding . |
| BindingMemberInfo |
Lekéri a konstruktor paramétere |
| Control |
Lekéri azt a vezérlőt, amelyhez a kötés tartozik. |
| ControlUpdateMode |
Lekérdezi vagy beállítja, ha az adatforrás módosításait a rendszer a kötött vezérlőelem tulajdonságra propagálja. |
| DataSource |
Lekéri a kötés adatforrását. |
| DataSourceNullValue |
Lekéri vagy beállítja az adatforrásban tárolni kívánt értéket, ha a vezérlőelem értéke |
| DataSourceUpdateMode |
Lekéri vagy beállítja azt az értéket, amely jelzi, hogy a kötött vezérlő tulajdonság módosításait a rendszer propagálja az adatforrásba. |
| FormatInfo |
Lekéri vagy beállítja az IFormatProvider egyéni formázási viselkedést. |
| FormatString |
Lekéri vagy beállítja azokat a formátumjelölő karaktereket, amelyek jelzik az érték megjelenítésének módját. |
| FormattingEnabled |
Lekéri vagy beállít egy értéket, amely jelzi, hogy a típuskonverzió és a formázás alkalmazható-e a vezérlőtulajdonság adataira. |
| IsBinding |
Egy értéket kap, amely jelzi, hogy a kötés aktív-e. |
| NullValue |
Lekéri vagy beállítja a Object vezérlőtulajdonságként beállítani kívánt értéket, ha az adatforrás tartalmaz egy DBNull értéket. |
| PropertyName |
Lekéri a vezérlő adathoz kötött tulajdonságának nevét. |
Metódusok
| Name | Description |
|---|---|
| Equals(Object) |
Meghatározza, hogy a megadott objektum egyenlő-e az aktuális objektummal. (Öröklődés forrása Object) |
| GetHashCode() |
Ez az alapértelmezett kivonatoló függvény. (Öröklődés forrása Object) |
| GetType() |
Lekéri az Type aktuális példányt. (Öröklődés forrása Object) |
| MemberwiseClone() |
Az aktuális Objectpéldány sekély másolatát hozza létre. (Öröklődés forrása Object) |
| OnBindingComplete(BindingCompleteEventArgs) |
Az eseményt emeli BindingComplete ki. |
| OnFormat(ConvertEventArgs) |
Az eseményt emeli Format ki. |
| OnParse(ConvertEventArgs) |
Az eseményt emeli Parse ki. |
| ReadValue() |
A vezérlőtulajdonságot az adatforrásból beolvasott értékre állítja. |
| ToString() |
Az aktuális objektumot jelképező sztringet ad vissza. (Öröklődés forrása Object) |
| WriteValue() |
Beolvassa az aktuális értéket a vezérlőtulajdonságból, és beírja az adatforrásba. |
esemény
| Name | Description |
|---|---|
| BindingComplete |
Ez akkor fordul elő, ha a FormattingEnabled tulajdonság be van állítva |
| Format |
Akkor fordul elő, ha egy vezérlőelem tulajdonsága adatértékhez van kötve. |
| Parse |
Akkor fordul elő, ha egy adathoz kötött vezérlő értéke megváltozik. |