October 8, 2008

[.NET] - Bind two controls to the same data source with synchronization

Photobucket

This is very common problem, as a newcomer I had spent great deal of time to solve this. Suppose you have two controls viz, Combobox and Listbox on same form and Datasource property of both these controls is same. Then the selection in one control selects same item in other control. This problem occurs because of BindingContext property of controls. By default the BindingContext member of each of the two controls is set to the Form's BindingContext. Thus, the default behavior is for the ComboBox and Listbox to share the same BindingContext, and that's why the selection in the ComboBox is synchronized with the current item of Listbox. If you do not want this behavior, create a new BindingContext member for at least one of the controls.

comboBox1.DataSource = dataset.Tables[ "Items" ]; 
comboBox1.ValueMember = "CustomerID"; 
comboBox1.DisplayMember = "CustomerID"; 

// Set the BindingContext property of ListBox to new BindingContext
listBox1.BindingContext = new BindingContext(); 
listBox1.DataSource = dataset.Tables[ "Items" ]; 
listBox1.ValueMember = "CustomerID"; 
listBox1.DisplayMember = "CustomerID";

No comments: