Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 688
Jerry Avatar asked Jan 11 '10 19:01

Jerry


2 Answers

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

like image 90
Corne Schriek Avatar answered Oct 27 '22 04:10

Corne Schriek


A ToolStripButton does not take the Focus when clicked. You could add some code to (temporarily) focus another control. You can Focus a Label (as a neutral dummy).

like image 38
Henk Holterman Avatar answered Oct 27 '22 02:10

Henk Holterman