C# Databound Windows Forms control does not retain value unless you leave the field

c#, data-binding, winforms

Solution

The problem is probably that your databound controls are set to update on validation.

You need to set the DataSourceUpdateMode of each of the databound controls to DataSourceUpdateMode.OnPropertyChanged. For example, a databound textbox:

this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", 
    this.someBindingSource, "SomeProperty", true, 
    System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

You can also set the datasource update mode in the designer by :

Selecting the control and going to the Property Window -> (DataBindings) -> (Advanced)

-> Set the [Data Source Update Mode] in the dropdownlist to OnPropertyChanged.

cheers

Problem

I saw the answer in Databound Windows Forms control does not recognize change until losing focus. But this doesn't fully answer the question for me. I have the exact same situation. On ToolStrip_click, I go through all of my controls and I force "WriteValue()", but it still reverts to the previous value before the save. Can anyone suggest how I can fix this? Did I implement this incorrectly? (See code for current (non-working) solution.) ``` private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { // Make sure that all items have updated databindings. foreach (Control C in this.Controls) { foreach (Binding b in C.DataBindings) { // Help: this doesn't seem to be working. b.WriteValue(); } } } ``` The code is now much simpler, but it is a considerable hack. I'd be very happy to know if there is a more "proper" fix for this. ``` private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { // Make sure that all text fields have updated by forcing everything // to lose focus except this lonely little label. label44.Focus(); } ```

Original source

Related problems