Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox not updating DataBindings on selected item changed (WinForms)

I have a ComboBox bound to a data source but it will not update the bindings until the control loses focus. How can I get the bindings to update when the selected items change? In the screen shot below I'd like the label to updated immediately to reflect the new selection.

Some Code:

public enum MyEnum
{
  First,
  Second
}

public class MyData
{
  public String Name { get; set; }
  public MyEnum MyEnum { get; set; }
}  

Sample Form:

public SampleForm()
{
  InitializeComponent ();   
  MyData data = new MyData () { Name = "Single Item" };
  this.bindingSource1.DataSource = data;
  this.comboBox1.DataSource = Enum.GetValues (typeof (MyEnum));
  this.label2.DataBindings.Add ("Text", this.bindingSource1, "MyEnum", true, DataSourceUpdateMode.OnPropertyChanged);
  this.comboBox1.DataBindings.Add (new System.Windows.Forms.Binding ("SelectedItem", this.bindingSource1, "MyEnum", true));
  this.comboBox1.DataBindings.Add (new System.Windows.Forms.Binding ("SelectedValue", this.bindingSource1, "MyEnum", true));
}
like image 495
kbeal2k Avatar asked Oct 23 '13 21:10

kbeal2k


2 Answers

Comment out the SelectedItem version, and modify the SelectedValue binding like this to include the UpdateMode:

this.comboBox1.DataBindings.Add(new Binding(
                                      "SelectedValue",
                                      this.bindingSource1,
                                      "MyEnum",
                                      true,
                                      DataSourceUpdateMode.OnPropertyChanged));
like image 122
LarsTech Avatar answered Nov 15 '22 09:11

LarsTech


LarsTech solution is correct. You can also do it in design mode:

  1. ComboBox Properties (F4) -> DataBindings node -> Advanced

  1. Click on 'SelectedValue' and change Data Source Update Mode to 'OnPropertyChanged' enter image description here
like image 39
mggSoft Avatar answered Nov 15 '22 08:11

mggSoft