Search code examples
c#winformsdata-bindingtextboxentity-framework-6

Why does a Bound Textbox not modify its associated property is the Text value is set programmatically?


I have a Windows Form with a number of Textboxes. I bind them to a DataSource as the Form Loads.

public partial class FormSettings : Form
{
    private readonly DbContext _context = new DbContext();

    public FormSettings()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        _context.OrderEntrySettings.Load();

        SettingsBindingSource.DataSource = _context.OrderEntrySettings.Local.ToBindingList();

        Binding saNbinding = new Binding("Text", SettingsBindingSource, "InvoiceNumber");

        InvoiceNumberTextBox.DataBindings.Add(saNbinding);

        Binding pthNbinding = new Binding("Text", SettingsBindingSource, "SalesOrderExportPath");

        PathTextBox.DataBindings.Add(pthNbinding);

    <snip>
    …   
    </snip>
}

One of the Textboxes is bound to a Directory Path (string) Property. If I type in a new directory in the Path Textbox and hit my save button, The path saves just fine.

But, If I change the Text Property on the Textbox to the SelectedPath from a FolderBrowserDialog dialog and then hit save, the Textbox Text shows the directory I selected but the Entity is not modified and nothing gets saved back to the database.

As a workaround, I set both the Path Textbox Text and set the Property from the context to the SelectedPath.

Why does a Bound Textbox not modify its associated property if the Text value is set programmatically?


Solution

  • Here is the reason. Binding class has a property called DataSourceUpdateMode with 3 options - Never, OnPropertyChanged and OnValidation, the last being a default. When you set the Text property programatically, there is no validating/validated events because they fire only when the control is on focus and has been edited, so the binding does not update the data source.

    That being said, here are the options you have:

    (A) Do not set the control property programatically, set the data source property instead.

    (B) Change the binding DataSourceUpdateMode to OnPropertyChanged. This however will cause the data source property to be updated on every char that the user is typing.

    (C) Use the following snippet:

    yourTextBox.Text = ...;
    yourTextBox.DataBindings["Text"].WriteValue();