Friday, June 8, 2007

Programmatic databinding between classes and controls

It's possible to programmatically databind to controls with the following statement:

myLabel.DataBindings.Add("Text", myObject, "Name");

However there are some specific controls that have trouble using databinding. Some should use another property, like Value or SelectedItem, while others need a specific
DataSourceUpdateMode. From my experience here's a list of controls and possible databindings:

  • Label
    myLabel.DataBindings.Add("Text", myObject, "Name");
  • TextBox
    myLabel.DataBindings.Add("Text", myObject, "Name");
  • NumericUpDown
    myNumericUpDown.DataBindings.Add("Text", myObject, "Age");
  • ComboBox
    mycomboBox.DataBindings.Add("SelectedItem", myObject, "Option", false, DataSourceUpdateMode.OnPropertyChanged);