Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

Why doesn't my DataGrid control stay in sync with my TextBox Control?

When two controls using the same data source are not synchronized, it is because they are using different CurrencyManagers.  There are two common ways in which controls bound to the same data source have different CurrencyManagers: the first is they have specified their data sources using different syntax (this is the more common of the two - see sample below) and the second is they using a different BindingContext.

Sample: Control Synchronization (VS 2005) (VS Project: CurrencyAndBindingContext)

/* Create a DataSet with 1 DataTable */
DataSet     dataSet = new DataSet();
DataTable   dataTable = dataSet.Tables.Add("Numbers");

dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));

dataTable.Rows.Add(0, "Zero");
dataTable.Rows.Add(1, "One");

/*******************************************************************
* Bind the first DataGridView and TextBox to the "Numbers" table in
* dataSet.  The DataGridView will use BindingContext to get a
* CurrencyManager for the data source.  DataGridView1 will use
* the following form of BindingContext:
*
*   bmb = BindingContext[dataSet, "Numbers"];
* 
* The textBox1's Text Binding will also get a BindingManagerBase
* and will use the following BindingContext form:
*
*   bmb = BindingContext[dataSet, "Number"];
*
* Therefore both dataGridView1 and textBox1 will share the same
* BindingManagerBase (CurrencyManager). 
*******************************************************************/

this.dataGridView1.DataSource = dataSet;
this.dataGridView1.DataMember = "Numbers";

this.textBox1.DataBindings.Add("Text", dataSet, "Numbers.Name", true);

/*******************************************************************
* The variable "dataTable" contains the "Numbers" table.  Although
* the above DataGridView and TextBox are bound to this table using
* "DataSource" and "DataMember" form, they could have bound to the
* same Table (and data) by binding directly to "dataTable" as shown
* below.  When doing this, DataGridView2 will use the following form
* of BindingContext:
*
*   bmb = BindingContext[dataTable];
* 
* The textBox2's Text Binding will use the following BindingContext
* form:
*
*   bmb = BindingContext[dataTable];
*
* Therefore both dataGridView2 and textBox2 will share the same
* data source however they will not share the same CurrencyManager
* since they used different forms to specify their bindings. 
*******************************************************************/

this.dataGridView2.DataSource = dataTable;
this.textBox2.DataBindings.Add("Text", dataTable, "Name", true);


Page view counter