Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

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

Windows Forms FAQs

How do I prevent two controls bound to the same DataTable from sharing the same current position?

If you have two controls bound to the same data source, 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, by default 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 that's why the selection in the ComboBox is synchronized with the current row of the DataGrid. If you do not want this behavior, create a new BindingContext member for at least one of the controls.

using System;
using System.Data;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
  // ...

  private DataGrid dataGrid1;
  private ComboBox comboBox1;
  private DataTable dataTable1;

  private void Form1_Load( object sender, EventArgs e )
  {
    // dataGrid1 uses the Form's BindingContext
    dataGrid1.DataSource = dataTable1;

    // create a new BindingContext for the combobox
    comboBox1.BindingContext = new BindingContext();
    comboBox1.DataSource = dataTable1;
    comboBox1.DisplayMember = "Col1";
    comboBox1.ValueMember = "Col1";
  }
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter