Binding (Clase)
Actualización: noviembre 2007
Representa el enlace sencillo entre el valor de propiedad de un objeto y el valor de propiedad de un control.
Ensamblado: System.Windows.Forms (en System.Windows.Forms.dll)
Utilice la clase Binding para crear y mantener un enlace sencillo entre la propiedad de un control y la propiedad de un objeto o la propiedad del objeto actual en una lista de objetos.
Como ejemplo del primer caso, puede enlazar la propiedad Text de un control TextBox a la propiedad FirstName de un objeto Customer. Como ejemplo del segundo caso, puede enlazar la propiedad Text de un control TextBox a la propiedad FirstName de un DataTable que contiene clientes.
La clase Binding también permite aplicar formato a valores para su vista a través del evento Format y para recuperar valores con formato a través del evento Parse.
Al construir una instancia de Binding con el constructor Binding, debe especificar tres elementos:
-
El nombre de la propiedad del control que se va a enlazar.
-
El origen de datos.
-
La ruta de exploración que se resuelve en una lista o una propiedad del origen de datos. La ruta de navegación también se utiliza para crear la propiedad BindingMemberInfo del objeto.
Primero, hay que especificar el nombre de la propiedad de control con la que se desea enlazar los datos. Por ejemplo, para mostrar datos en un control TextBox, hay que especificar la propiedad Text.
En segundo lugar, puede especificar como origen de datos una instancia de cualquiera de las clases de la tabla siguiente.
|
Descripción |
Ejemplo de C# |
|---|---|
|
Cualquier clase que implemente IBindingList o ITypedList. Estas clases son, entre otras: DataSet, DataTable, DataView o DataViewManager. |
DataSet ds = new DataSet("myDataSet");
|
|
Cualquier clase que implemente IList para crear una colección indizada de objetos. Es necesario crear y llenar la colección antes de crear el Binding. Todos los objetos de la lista deben ser del mismo tipo; de lo contrario, se produce una excepción. |
ArrayList ar1 = new ArrayList;
Customer1 cust1 = new Customer("Louis");
ar1.Add(cust1);
|
|
Una IList con establecimiento inflexible de tipos de objetos con establecimiento inflexible de tipos |
Customer [] custList = new Customer[3]; |
En tercer lugar, hay que especificar la ruta de navegación, que puede ser una cadena vacía (""), un único nombre de propiedad o una jerarquía de nombres delimitados mediante un punto. Si se establece la ruta de navegación en una cadena vacía, se llamará al método ToString en el objeto de origen de datos subyacente.
Si el origen de datos es DataTable, que puede contener múltiples objetos DataColumn, debe usarse la ruta de navegación para resolver una columna específica.
Nota:
|
|---|
|
Cuando el origen de datos es DataSet, DataViewManager o DataTable, en realidad se está creando un enlace a DataView. En consecuencia, las filas enlazadas son realmente objetos DataRowView. |
Se requiere una ruta de navegación delimitada por puntos cuando el origen de datos se establece en un objeto que contiene múltiples objetos DataTable (como DataSet o DataViewManager). También se puede usar una ruta de navegación delimitada por puntos cuando se crea un enlace con un objeto cuyas propiedades devuelven referencias a otros objetos (como una clase con propiedades que devuelven otros objetos de clase). Por ejemplo, todas las rutas de navegación siguientes describen campos de datos válidos:
-
"Size.Height"
-
"Suppliers.CompanyName"
-
"Regions.regionsToCustomers.CustomerFirstName"
-
"Regions.regionsToCustomers.customersToOrders.ordersToDetails.Quantity"
Cada miembro de la ruta puede devolver una propiedad que resuelva un solo valor (por ejemplo, un entero) o una lista de valores (como una matriz de cadenas). Aunque cada miembro de la ruta puede ser una lista o una propiedad, el último miembro debe resolver una propiedad. Cada miembro toma como base el miembro anterior: "Size.Height" resuelve la propiedad Height para el objeto Size actual; "Regions.regionsToCustomers.CustomerFirstName" resuelve el nombre del cliente actual, donde el cliente es uno de los clientes de la región actual.
DataRelation devuelve una lista de valores al vincular un objeto DataTable a un segundo objeto DataTable en un DataSet. Si DataSet contiene objetos DataRelation, es posible especificar el miembro de datos como TableName seguido de RelationName y, después, ColumnName. Por ejemplo, si el objeto DataTable denominado "Suppliers" contiene un objeto DataRelation denominado "suppliers2products", el miembro de datos podría ser "Suppliers.suppliers2products.ProductName".
El origen de datos puede consistir en un conjunto de clases relacionadas. Imaginemos, por ejemplo, un conjunto de clases que catalogue sistemas solares. La clase denominada System contiene una propiedad denominada Stars que devuelve una colección de objetos Star. Cada objeto Star tiene propiedades Name y Mass, así como una propiedad Planets que devuelve una colección de objetos Planet. En este sistema, cada planeta tiene también las propiedades Mass y Name. Cada objeto Planet tiene además una propiedad Moons que devuelve una colección de objetos Moon, cada uno de los cuales tiene también las propiedades Name y Mass. Si especifica un objeto System como origen de datos, puede especificar cualquiera de lo siguiente como miembro de datos:
-
"Stars.Name"
-
"Stars.Mass"
-
"Stars.Planets.Name"
-
"Stars.Planets.Mass"
-
"Stars.Planets.Moons.Name"
-
"Stars.Planets.Moons.Mass"
Los controles que pueden tener un enlace sencillo representan una colección de objetos Binding en un objeto ControlBindingsCollection, al que se puede obtener acceso a través de la propiedad DataBindings del control. Para agregar un Binding a la colección, se llama al método Add, con lo que se enlaza una propiedad del control a una propiedad de un objeto (o a una propiedad del objeto actual de una lista).
Se puede crear un enlace sencillo con cualquier objeto que se derive de la clase System.Windows.Forms.Control; por ejemplo, los siguientes controles de Windows:
Nota:
|
|---|
|
Sólo la propiedad SelectedValue de los controles ComboBox, CheckedListBox y ListBox tiene un enlace sencillo. |
BindingManagerBase es una clase abstracta que administra todos los objetos Binding para un origen de datos y un miembro de datos concretos. Las clases que se derivan de BindingManagerBase son las clases CurrencyManager y PropertyManager. La forma en que se administra Binding depende de si Binding es un enlace a lista o un enlace a propiedad. Por ejemplo, si se trata de un enlace a lista, puede usar BindingManagerBase para especificar una Position de la lista; por tanto, Position determina qué elemento (de todos los elementos de la lista) está realmente enlazado a un control. Para devolver el valor de BindingManagerBase correspondiente, hay que utilizar BindingContext.
Para agregar una nueva fila a un conjunto de controles enlazados a la misma propiedad DataSource, hay que utilizar el método AddNew de la clase BindingManagerBase. Utilice la propiedad Item de la clase BindingContext para devolver el objeto CurrencyManager correspondiente. Para anular la inserción de la nueva fila, hay que utilizar el método CancelCurrentEdit.
En el ejemplo de código siguiente se crea un formulario Windows Forms con varios controles que muestran un enlace a datos sencillo. En el ejemplo, se crea un objeto DataSet con dos tablas denominadas Customers y Orders, y un objeto DataRelation denominado custToOrders. Cuatro controles (un control DateTimePicker y tres controles TextBox) tienen un enlace a datos con las columnas de las tablas. En cada control se crea y se agrega un objeto Binding al control en cuestión a través de la propiedad DataBindings. En el ejemplo se devuelve un BindingManagerBase para cada tabla a través del BindingContext del formulario. Hay cuatro controles Button que aumentan o disminuyen la propiedad Position de los objetos BindingManagerBase.
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); } } } }
import System.*;
import System.Data.*;
import System.Drawing.*;
import System.Globalization.*;
import System.Windows.Forms.*;
public class Form1 extends 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();
} //Form1
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.set_Text("Binding Sample");
this.set_ClientSize(new System.Drawing.Size(450, 200));
button1.set_Location(new System.Drawing.Point(24, 16));
button1.set_Size(new System.Drawing.Size(64, 24));
button1.set_Text("<");
button1.add_Click(new System.EventHandler(button1_Click));
button2.set_Location(new System.Drawing.Point(90, 16));
button2.set_Size(new System.Drawing.Size(64, 24));
button2.set_Text(">");
button2.add_Click(new System.EventHandler(button2_Click));
button3.set_Location(new System.Drawing.Point(90, 100));
button3.set_Size(new System.Drawing.Size(64, 24));
button3.set_Text("<");
button3.add_Click(new System.EventHandler(button3_Click));
button4.set_Location(new System.Drawing.Point(150, 100));
button4.set_Size(new System.Drawing.Size(64, 24));
button4.set_Text(">");
button4.add_Click(new System.EventHandler(button4_Click));
text1.set_Location(new System.Drawing.Point(24, 50));
text1.set_Size(new System.Drawing.Size(150, 24));
text2.set_Location(new System.Drawing.Point(190, 50));
text2.set_Size(new System.Drawing.Size(150, 24));
text3.set_Location(new System.Drawing.Point(290, 150));
text3.set_Size(new System.Drawing.Size(150, 24));
dateTimePicker1.set_Location(new System.Drawing.Point(90, 150));
dateTimePicker1.set_Size(new System.Drawing.Size(200, 800));
this.get_Controls().Add(button1);
this.get_Controls().Add(button2);
this.get_Controls().Add(button3);
this.get_Controls().Add(button4);
this.get_Controls().Add(text1);
this.get_Controls().Add(text2);
this.get_Controls().Add(text3);
this.get_Controls().Add(dateTimePicker1);
} //InitializeComponent
protected void Dispose(boolean disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
super.Dispose(disposing);
} //Dispose
public static void main(String[] args)
{
Application.Run(new Form1());
} //main
private void SetUp()
{
// Create a DataSet with two tables and one relation.
MakeDataSet();
BindControls();
} //SetUp
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.get_DataBindings().Add(new Binding("Text", ds,
"customers.custName"));
text2.get_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.get_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.add_Parse(new ConvertEventHandler(CurrencyStringToDecimal));
b.add_Format(new ConvertEventHandler(DecimalToCurrencyString));
text3.get_DataBindings().Add(b);
// Get the BindingManagerBase for the Customers table.
bmCustomers = this.get_BindingContext().get_Item(ds, "Customers");
/* Get the BindingManagerBase for the Orders table using the
RelationName.
*/
bmOrders = this.get_BindingContext().get_Item(ds,
"customers.CustToOrders");
} //BindControls
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.get_DesiredType().Equals(String.class.ToType())) {
return;
}
cevent.set_Value(((System.Decimal)(cevent.get_Value())).ToString("c"));
} //DecimalToCurrencyString
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.get_DesiredType().Equals(System.Decimal.class.ToType())) {
return;
}
cevent.set_Value(Decimal.Parse(cevent.get_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.get_Value());
} //CurrencyStringToDecimal
private void button1_Click(Object sender, System.EventArgs e)
{
// Go to the previous item in the Customer list.
bmCustomers.set_Position(bmCustomers.get_Position() - 1);
} //button1_Click
private void button2_Click(Object sender, System.EventArgs e)
{
// Go to the next item in the Customer list.
bmCustomers.set_Position(bmCustomers.get_Position() + 1);
} //button2_Click
private void button3_Click(Object sender, System.EventArgs e)
{
// Go to the previous item in the Orders list.
bmOrders.set_Position(bmOrders.get_Position() - 1);
} //button3_Click
private void button4_Click(Object sender, System.EventArgs e)
{
// Go to the next item in the Orders list.
bmOrders.set_Position(bmOrders.get_Position() + 1);
} //button4_Click
// 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", int.class.ToType());
DataColumn cCustName = new DataColumn("CustName");
tCust.get_Columns().Add(cCustID);
tCust.get_Columns().Add(cCustName);
// Create three columns, and add them to the second table.
DataColumn cID = new DataColumn("CustID", int.class.ToType());
DataColumn cOrderDate = new DataColumn("orderDate",
DateTime.class.ToType());
DataColumn cOrderAmount = new DataColumn("OrderAmount",
System.Decimal.class.ToType());
tOrders.get_Columns().Add(cOrderAmount);
tOrders.get_Columns().Add(cID);
tOrders.get_Columns().Add(cOrderDate);
// Add the tables to the DataSet.
ds.get_Tables().Add(tCust);
ds.get_Tables().Add(tOrders);
// Create a DataRelation, and add it to the DataSet.
DataRelation dr = new DataRelation("custToOrders", cCustID, cID);
ds.get_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.set_Item("custID", (Int32)i);
// Add the row to the Customers table.
tCust.get_Rows().Add(newRow1);
}
// Give each customer a distinct name.
tCust.get_Rows().get_Item(0).set_Item("custName", "Alpha");
tCust.get_Rows().get_Item(1).set_Item("custName", "Beta");
tCust.get_Rows().get_Item(2).set_Item("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.set_Item("CustID", (Int32)i);
newRow2.set_Item("orderDate", new DateTime(2001, i, j * 2));
newRow2.set_Item("OrderAmount",
(System.Double)(i * 10 + j * 0.1));
// Add the row to the Orders table.
tOrders.get_Rows().Add(newRow2);
}
}
} //MakeDataSet
} //Form1
import System; import System.Data; import System.Drawing; import System.Globalization; import System.Windows.Forms; public class Form1 extends System.Windows.Forms.Form { private var components : System.ComponentModel.Container; private var button1 : Button; private var button2 : Button; private var button3 : Button; private var button4 : Button; private var text1 : TextBox; private var text2 : TextBox; private var text3 : TextBox; private var bmCustomers : BindingManagerBase; private var bmOrders : BindingManagerBase; private var ds : DataSet; private var DateTimePicker1 : DateTimePicker; public function Form1() { // Required for Windows Form Designer support. InitializeComponent(); // Call SetUp to bind the controls. SetUp(); } private function 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.add_Click(button1_Click); button2.Location = new System.Drawing.Point(90, 16); button2.Size = new System.Drawing.Size(64, 24); button2.Text = ">"; button2.add_Click(button2_Click); button3.Location = new System.Drawing.Point(90, 100); button3.Size = new System.Drawing.Size(64, 24); button3.Text = "<"; button3.add_Click(button3_Click); button4.Location = new System.Drawing.Point(150, 100); button4.Size = new System.Drawing.Size(64, 24); button4.Text = ">"; button4.add_Click(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 function Dispose(disposing : boolean){ if( disposing ){ if (components != null){ components.Dispose();} } super.Dispose( disposing ); } public static function Main() { Application.Run(new Form1()); } private function SetUp() { // Create a DataSet with two tables and one relation. MakeDataSet(); BindControls(); } protected function 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. */ var b : Binding = new Binding ("Text", ds, "customers.custToOrders.OrderAmount"); b.add_Parse(CurrencyStringToDecimal); b.add_Format(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 function DecimalToCurrencyString(sender, cevent : 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 != String.GetType()) return; cevent.Value = (Decimal(cevent.Value)).ToString("c"); } private function CurrencyStringToDecimal(sender, cevent : 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 != Decimal.GetType()) 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 function button1_Click(sender, e : System.EventArgs) { // Go to the previous item in the Customer list. bmCustomers.Position -= 1; } private function button2_Click(sender, e : System.EventArgs) { // Go to the next item in the Customer list. bmCustomers.Position += 1; } private function button3_Click(sender, e : System.EventArgs) { // Go to the previous item in the Orders list. bmOrders.Position-=1; } private function button4_Click(sender, e : System.EventArgs) { // Go to the next item in the Orders list. bmOrders.Position+=1; } // Create a DataSet with two tables and populate it. private function MakeDataSet() { // Create a DataSet. ds = new DataSet("myDataSet"); // Create two DataTables. var tCust : DataTable = new DataTable("Customers"); var tOrders : DataTable= new DataTable("Orders"); // Create two columns, and add them to the first table. var cCustID : DataColumn = new DataColumn("CustID", Int32); var cCustName : DataColumn = new DataColumn("CustName"); tCust.Columns.Add(cCustID); tCust.Columns.Add(cCustName); // Create three columns, and add them to the second table. var cID : DataColumn = new DataColumn("CustID", Int32); var cOrderDate : DataColumn = new DataColumn("orderDate", DateTime); var cOrderAmount : DataColumn = new DataColumn("OrderAmount", 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. var dr : DataRelation = new DataRelation ("custToOrders", cCustID , cID); ds.Relations.Add(dr); /* Populate the tables. For each customer and order, create two DataRow variables. */ var newRow1 : DataRow; var newRow2 : DataRow; // Create three customers in the Customers Table. for(var i : int = 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(var j : int = 1; j < 4; j++) { for(var k : int = 1; k < 6; k++) { newRow2 = tOrders.NewRow(); newRow2["CustID"]= j; newRow2["orderDate"]= new DateTime(2001, j, k * 2); newRow2["OrderAmount"] = j * 10 + k * .1; // Add the row to the Orders table. tOrders.Rows.Add(newRow2); } } } }
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC
.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Nota: