Live Chat Icon For mobile
Live Chat Icon

How can I prevent a ComboBox and DataGrid bound to the same DataTable from sharing the same current position

Platform: WinForms| Category: Data Binding

If you have two controls bound to the same datasource, and you do not want them to share the same position, then you must make sure that the BindingContext member of one control differs from the BindingContext member of the other control. If they have the same BindingContext, they will share the same position in the datasource.

If you add a ComboBox and a DataGrid to a form, the default behavior is for the BindingContext member of each of the two controls to be set to the Form’s BindingContext. Thus, the default behavior is for the DataGrid and ComboBox to share the same BindingContext, and hence the selection in the ComboBox is synchronized with the current row of the DataGrid. If you do not want this behavior, you should create a new BindingContext member for at least one of the controls.

[C#]
private void Form1_Load(object sender, System.EventArgs e)
{
	this.myDataTable = GetATable(); //get a datatable somehow...

	this.dataGrid1.DataSource = myDataTable;

	//set a new binding context for the combobox
	this.comboBox1.BindingContext = new BindingContext();
	this.comboBox1.DataSource = myDataTable;
	this.comboBox1.DisplayMember = 'Col1';
	this.comboBox1.ValueMember = 'Col1';
}

[VB.NET]
Private Sub Form1_Load(ByVal sender as Object, ByVal e as  System.EventArgs)
 
	Me.myDataTable = GetATable() ’get a datatable somehow...

	Me.dataGrid1.DataSource = myDataTable

	’set a new binding context for the combobox
	Me.comboBox1.BindingContext = New BindingContext()
	Me.comboBox1.DataSource = myDataTable
	Me.comboBox1.DisplayMember = 'Col1'
	Me.comboBox1.ValueMember = 'Col1'
End Sub

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.