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 Form을 만듭니다. 이 예제에서는 명명된 DataSet 두 개의 테이블과 Orders명명 CustomerscustToOrders된 DataRelation 테이블을 만듭니다. 4개의 컨트롤(a DateTimePicker 및 3 TextBox 개의 컨트롤)은 테이블의 열에 바인딩된 데이터입니다. 각 컨트롤에 대해 이 예제에서는 속성을 통해 컨트롤을 만들고 컨트롤에 DataBindings 추가 Binding 합니다. 이 예제에서는 폼을 BindingManagerBase 통해 각 테이블에 대한 값을 반환합니다 BindingContext. 4개의 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 사용하여 컨트롤의 속성과 개체의 속성 또는 개체 목록에서 현재 개체의 속성 간에 간단한 바인딩을 만들고 유지 관리할 수 있습니다.
첫 번째 사례의 예로 컨트롤의 속성을 개체의 TextBoxCustomer 속성에 FirstName 바인딩 Text 할 수 있습니다. 두 번째 사례의 예로 컨트롤의 TextBox 속성을 고객이 포함된 속성에 DataTable 바인딩 Text 할 FirstName 수 있습니다.
또한 클래스 Binding 를 사용하면 이벤트를 통해 표시할 값의 서식을 Format 지정하고 이벤트를 통해 Parse 형식이 지정된 값을 검색할 수 있습니다.
생성자를 사용하여 인스턴스 Binding 를 Binding 생성할 때 다음 세 개의 항목을 지정해야 합니다.
바인딩할 컨트롤 속성의 이름입니다.
데이터 원본입니다.
데이터 원본의 목록 또는 속성으로 확인되는 탐색 경로입니다. 탐색 경로는 개체의 BindingMemberInfo 속성을 만드는 데도 사용됩니다.
먼저 데이터를 바인딩할 컨트롤 속성의 이름을 지정해야 합니다. 예를 들어 컨트롤에 TextBox 데이터를 표시하려면 속성을 지정합니다 Text .
둘째, 다음 표에 있는 클래스 중 하나의 인스턴스를 데이터 원본으로 지정할 수 있습니다.
| 설명 | C# 예제 |
|---|---|
| 구현 IBindingList 하는 모든 클래스 또는 ITypedList. 여기에는 다음 DataSet이 포함되며 , DataTable, DataView또는 DataViewManager. | DataSet ds = new DataSet("myDataSet"); |
| 인덱싱 IList 된 개체 컬렉션을 만들기 위해 구현하는 모든 클래스입니다. 컬렉션을 만들고 채워 Binding야 합니다. 목록의 개체는 모두 동일한 형식이어야 합니다. 그렇지 않으면 예외가 throw됩니다. | ArrayList ar1 = new ArrayList; Customer1 cust1 = new Customer("Louis"); ar1.Add(cust1); |
| 강력한 형식 IList 의 강력한 형식의 개체 | Customer [] custList = new Customer[3]; |
셋째, 빈 문자열(""), 단일 속성 이름 또는 기간으로 구분된 이름의 계층 구조일 수 있는 탐색 경로를 지정해야 합니다. 탐색 경로를 빈 문자열 ToString 로 설정하면 기본 데이터 원본 개체에서 메서드가 호출됩니다.
데이터 원본이 여러 DataColumn 개체를 DataTable포함할 수 있는 경우 탐색 경로를 사용하여 특정 열로 확인해야 합니다.
메모
데이터 원본이 <
데이터 원본이 여러 DataTable 개체(예: a 또는DataViewManager)를 포함하는 개체로 설정된 경우 마침표로 구분된 탐색 경로가 DataSet 필요합니다. 속성이 다른 개체(예: 다른 클래스 개체를 반환하는 속성이 있는 클래스)에 대한 참조를 반환하는 개체에 바인딩할 때 마침표로 구분된 탐색 경로를 사용할 수도 있습니다. 예를 들어 다음 탐색 경로는 모두 유효한 데이터 필드를 설명합니다.
"Size.Height"
"Suppliers.CompanyName"
"Regions.regionsToCustomers.CustomerFirstName"
"Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity"
경로의 각 멤버는 단일 값(예: 정수)으로 확인되는 속성 또는 값 목록(예: 문자열 배열)을 반환할 수 있습니다. 경로의 각 멤버는 목록 또는 속성일 수 있지만 최종 멤버는 속성으로 확인되어야 합니다. 각 멤버는 이전 멤버를 기반으로 합니다. "Size.Height"는 현재Size에 대한 속성으로 Height 확인됩니다. "Regions.regionsToCustomers.CustomerFirstName"은 현재 고객의 이름으로 확인됩니다. 여기서 고객은 현재 지역의 고객 중 하나입니다.
A DataRelation 는 1을 1초에 DataSet연결 DataTableDataTable 하여 값 목록을 반환합니다. 개체가 DataSetDataRelation 포함된 경우 데이터 멤버를 다음으로 TableName 지정한 RelationName다음 ColumnName. 예를 들어 명명된 "Suppliers"에 명명된 "suppliers2products"가 포함된 DataRelation 경우 DataTable 데이터 멤버는 "Suppliers.suppliers2products.ProductName"일 수 있습니다.
데이터 원본은 일련의 관련 클래스로 구성됩니다. 예를 들어 태양광 시스템을 카탈로그로 만드는 클래스 집합을 상상해 보십시오. 명명된 System 클래스에는 개체 컬렉션을 Star 반환하는 속성 Stars 이 포함되어 있습니다. 각 Star 개체에는 NameMass 개체 컬렉션을 Planet 반환하는 속성과 Planets 속성이 있습니다. 이 시스템에서 각 행성에는 또한 속성과 속성이 Mass 있습니다 Name . 각 Planet 개체에는 Moons 개체 컬렉션을 Moon 반환하는 속성이 있으며, 각 개체에는 속성도 있습니다 NameMass . 개체를 System 데이터 원본으로 지정하는 경우 다음 중 원하는 항목을 데이터 멤버로 지정할 수 있습니다.
"Stars.Name"
"Stars.Mass"
"Stars.Planets.Name"
"Stars.Planets.Mass"
"Stars.Planets.Moons.Name"
"Stars.Planets.Moons.Mass"
단순 바인딩될 수 있는 컨트롤은 컨트롤의 속성을 통해 DataBindings 액세스할 수 있는 개체 ControlBindingsCollection컬렉션을 Binding 특징으로 합니다. 메서드를 Binding 호출 Add 하여 컬렉션에 추가하면 컨트롤의 속성을 개체의 속성(또는 목록의 현재 개체 속성)에 바인딩합니다.
클래스에서 System.Windows.Forms.Control 파생되는 모든 개체(예: 다음 Windows 컨트롤)에 단순 바인딩할 수 있습니다.
메모
및 SelectedValue 컨트롤의 ComboBoxCheckedListBoxListBox 속성만 단순 바인딩됩니다.
클래스 BindingManagerBase 는 특정 데이터 원본 및 데이터 멤버에 Binding 대한 모든 개체를 관리하는 추상 클래스입니다. 파생 BindingManagerBase 되는 클래스는 CurrencyManager 클래스와 PropertyManager 클래스입니다. Binding 관리 방법은 목록 바인딩인지 속성 바인딩인지에 Binding 따라 달라집니다. 예를 들어 목록 바인딩인 경우 목록에서 지정 Position 하는 데 사용할 BindingManagerBase 수 있습니다. 따라서 목록Position의 모든 항목 중에서 실제로 컨트롤에 바인딩되는 항목을 결정합니다. 적절한 BindingManagerBase값을 반환하려면 .를 BindingContext사용합니다.
동일한 DataSource컨트롤에 바인딩된 컨트롤 집합에 새 행을 추가하려면 클래스의 메서드를 AddNewBindingManagerBase 사용합니다. 클래스의 Item[]BindingContext 속성을 사용하여 적절한 CurrencyManager값을 반환합니다. 새 행의 추가를 이스케이프하려면 메서드를 CancelCurrentEdit 사용합니다.
생성자
| Name | Description |
|---|---|
| Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object, String, IFormatProvider) |
지정된 컨트롤 속성을 사용하여 지정된 데이터 원본의 Binding 지정된 데이터 멤버에 대한 클래스의 새 인스턴스를 초기화합니다. 필요에 따라 지정된 형식 문자열을 사용하여 서식 지정을 사용하도록 설정합니다. 지정된 업데이트 설정에 따라 값을 데이터 원본에 전파합니다. 에서는 지정된 형식 문자열을 사용하여 서식을 지정할 수 있습니다. 는 데이터 원본에서 반환될 때 속성을 지정된 값으로 DBNull 설정하고 지정된 형식 공급자를 설정합니다. |
| Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object, String) |
지정된 컨트롤 속성을 지정된 데이터 원본의 Binding 지정된 데이터 멤버에 바인딩하는 클래스의 새 인스턴스를 초기화합니다. 필요에 따라 지정된 형식 문자열을 사용하여 서식 지정을 사용하도록 설정합니다. 지정된 업데이트 설정에 따라 값을 데이터 원본에 전파합니다. 데이터 원본에서 반환될 때 속성을 지정된 값으로 DBNull 설정합니다. |
| Binding(String, Object, String, Boolean, DataSourceUpdateMode, Object) |
지정된 컨트롤 속성을 지정된 데이터 원본의 Binding 지정된 데이터 멤버에 바인딩하는 클래스의 새 인스턴스를 초기화합니다. 필요에 따라 서식을 사용하도록 설정하고, 지정된 업데이트 설정에 따라 데이터 원본에 값을 전파하고, 데이터 원본에서 반환될 때 속성을 지정된 값으로 DBNull 설정합니다. |
| Binding(String, Object, String, Boolean, DataSourceUpdateMode) |
지정된 컨트롤 속성을 지정된 데이터 원본의 Binding 지정된 데이터 멤버에 바인딩하는 클래스의 새 인스턴스를 초기화합니다. 필요에 따라 서식을 사용하도록 설정하고 지정된 업데이트 설정에 따라 데이터 원본에 값을 전파합니다. |
| Binding(String, Object, String, Boolean) |
지정된 컨트롤 속성을 데이터 원본의 Binding 지정된 데이터 멤버에 바인딩하고 필요에 따라 서식을 적용할 수 있도록 하는 클래스의 새 인스턴스를 초기화합니다. |
| Binding(String, Object, String) |
지정된 컨트롤 속성을 데이터 원본의 Binding 지정된 데이터 멤버에 간단하게 바인딩하는 클래스의 새 인스턴스를 초기화합니다. |
속성
| Name | Description |
|---|---|
| BindableComponent |
연결된 컨트롤을 Binding 가져옵니다. |
| BindingManagerBase |
에 BindingManagerBase대한 값을 Binding 가져옵니다. |
| BindingMemberInfo |
생성자의 매개 변수를 기반으로 |
| Control |
바인딩이 속한 컨트롤을 가져옵니다. |
| ControlUpdateMode |
데이터 원본에 대한 변경 내용이 바인딩된 컨트롤 속성으로 전파되는 경우를 가져오거나 설정합니다. |
| DataSource |
이 바인딩의 데이터 원본을 가져옵니다. |
| DataSourceNullValue |
컨트롤 값이 있거나 비어 있는 경우 데이터 원본에 저장할 값을 |
| DataSourceUpdateMode |
바인딩된 컨트롤 속성의 변경 내용이 데이터 원본으로 전파되는 시기를 나타내는 값을 가져오거나 설정합니다. |
| FormatInfo |
사용자 지정 서식 동작을 IFormatProvider 제공하는 값을 가져오거나 설정합니다. |
| FormatString |
값을 표시하는 방법을 나타내는 형식 지정자 문자를 가져오거나 설정합니다. |
| FormattingEnabled |
형식 변환 및 서식이 컨트롤 속성 데이터에 적용되는지 여부를 나타내는 값을 가져오거나 설정합니다. |
| IsBinding |
바인딩이 활성 상태인지 여부를 나타내는 값을 가져옵니다. |
| NullValue |
데이터 원본에 값이 Object 포함된 DBNull 경우 컨트롤 속성으로 설정할 값을 가져오거나 설정합니다. |
| PropertyName |
컨트롤의 데이터 바인딩된 속성의 이름을 가져옵니다. |
메서드
| Name | Description |
|---|---|
| Equals(Object) |
지정된 개체가 현재 개체와 같은지 여부를 확인합니다. (다음에서 상속됨 Object) |
| GetHashCode() |
기본 해시 함수로 사용됩니다. (다음에서 상속됨 Object) |
| GetType() |
현재 인스턴스의 Type 가져옵니다. (다음에서 상속됨 Object) |
| MemberwiseClone() |
현재 Object단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
| OnBindingComplete(BindingCompleteEventArgs) |
BindingComplete 이벤트를 발생시킵니다. |
| OnFormat(ConvertEventArgs) |
Format 이벤트를 발생시킵니다. |
| OnParse(ConvertEventArgs) |
Parse 이벤트를 발생시킵니다. |
| ReadValue() |
컨트롤 속성을 데이터 원본에서 읽은 값으로 설정합니다. |
| ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
| WriteValue() |
컨트롤 속성에서 현재 값을 읽고 데이터 원본에 씁니다. |
이벤트
| Name | Description |
|---|---|
| BindingComplete |
컨트롤에서 데이터 원본으로 |
| Format |
컨트롤의 속성이 데이터 값에 바인딩된 경우에 발생합니다. |
| Parse |
데이터 바인딩된 컨트롤의 값이 변경되면 발생합니다. |