Export (0) Print
Expand All

BindingContext Class

Manages the collection of BindingManagerBase objects for any object that inherits from the Control class.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)

public class BindingContext : ICollection, IEnumerable
public class BindingContext implements ICollection, IEnumerable
public class BindingContext implements ICollection, IEnumerable

Each Windows Form has at least one BindingContext object that manages the BindingManagerBase objects for the form. Because the BindingManagerBase class is abstract, the return type of the Item property is either a CurrencyManager or a PropertyManager. If the data source is an object that can return only a single property (instead of a list of objects), the Type is a PropertyManager. For example, if you specify a TextBox as the data source, a PropertyManager is returned. On the other hand, if the data source is an object that implements IList or IBindingList, a CurrencyManager is returned.

For each data source on a Windows Form, there is a single CurrencyManager or PropertyManager. Because there may be multiple data sources associated with a Windows Form, the BindingContext enables you to retrieve any particular CurrencyManager associated with a data source.

NoteNote

When using the Item property, the BindingContext creates a new BindingManagerBase if one does not already exist. This can lead to some confusion, as the returned object may not manage the list (or any list) that you intend. To prevent returning an invalid BindingManagerBase, use the Contains method to determine if the intended BindingManagerBase already exists.

If you use a container control, such as a GroupBox, Panel, or TabControl, to contain data-bound controls, you can create a BindingContext for just that container control and its controls. Then, each part of your form can be managed by its own BindingManagerBase. See the BindingContext constructor for more information about creating multiple BindingManagerBase objects for the same data source.

If you add a TextBox control to a form and bind it to a column of a table in a dataset, the control communicates with the BindingContext of that form. The BindingContext, in turn, talks to the specific CurrencyManager for that data association. If you queried the Position property of the CurrencyManager, it would report the current record for the binding of that TextBox control. In the following code example, a TextBox control is bound to the FirstName column of a Customers table on the dataSet1 dataset through the BindingContext for the form it is on.

textBox1.DataBindings.Add("Text", dataSet1, "Customers.FirstName");


You can add a second TextBox control (TextBox2) to the form and bind it to the LastName column of the Customers table in the same dataset. The BindingContext is aware of the first binding (TextBox1 to Customers.FirstName), so it would use the same CurrencyManager, as both text boxes are bound to the same dataset (DataSet1).

textBox2.DataBindings.Add("Text", dataSet1, "Customers.LastName");


If you bind TextBox2 to a different dataset, the BindingContext creates and manages a second CurrencyManager.

It is important to be consistent about how you set the DataSource and DisplayMember properties; otherwise, the BindingContext creates multiple currency managers for the same dataset, which results in errors. The following code example shows a few ways to set the properties and their associated BindingContext objects. You can set the properties using either of the following methods, as long as you are consistent throughout your code.

comboBox1.DataSource = DataSet1;
comboBox1.DisplayMember = "Customers.FirstName";
this.BindingContext[dataSet1, "Customers"].Position = 1;


comboBox1.DataSource = DataSet1.Customers;
comboBox1.DisplayMember = "FirstName";
this.BindingContext[dataSet1.Customers].Position = 1;


NoteNote

Most Windows Forms applications bind through a BindingSource. The BindingSource component encapsulates a CurrencyManager and exposes the CurrencyManager programming interface. When using a BindingSource for binding, you should use the members exposed by the BindingSource to manipulate "currency" (that is, Position) rather than go through the BindingContext.

The following code example creates four Binding objects to bind five controls—a DateTimePicker and four TextBox controls—to several data sources. The BindingContext is then used to get the BindingManagerBase for each data source.

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 a navigation path in the form: 
      "TableName.ColumnName". */
   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 navigation path:
      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"];

   /* Bind the fourth TextBox control's Text property to the
   third control's Text property. */
   text4.DataBindings.Add("Text", text3, "Text");
}


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 a navigation path in the form: 
       "TableName.ColumnName". 
     */
    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 navigation path:
       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");

    /* Bind the fourth TextBox control's Text property to the
       third control's Text property. 
     */
    text4.get_DataBindings().Add("Text", text3, "Text");
} //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 string 
        "TableName.ColumnName". */
     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". */

     // We 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);
  }

  protected function button1_Click(sender, e : System.EventArgs)
  {
     // Go to the previous item in the Customer list.
     bmCustomers.Position -= 1;
  }

  protected function button2_Click(sender, e : System.EventArgs)
  {
     // Go to the next item in the Customer list.
     bmCustomers.Position += 1;
  }
   
  protected function button3_Click(sender, e : System.EventArgs)
  {
     // Go to the previous item in the Orders list.
     bmOrders.Position-=1;
  }

  protected 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 need 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);
        }
     }
  }
}


System.Object
  System.Windows.Forms.BindingContext

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft