简体   繁体   中英

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));
}

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));

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' 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM