Search code examples
c#winformsdata-bindingtextbox

Bound textbox shows database value, but the 'Text' property is an empty string


I can't seem to find any answers on what I would think is a pretty basic problem. I have a textbox that is bound to a dataset that gets filled on form load. When I run the program the value from the database is displayed in the textbox.

However, the text property is an empty string. If I click in the field and then leave it, the text value is set. Reading from, and even writing to, the database through the table adapter is working fine. I just can't seem to get a value into the text property.

Here's the relevant code...

Code added by Visual Studio when I bound the field through the user interface:

this.appSettingsBindingSource.DataMember = "AppSettings";
this.appSettingsBindingSource.DataSource = this.dSAppSettings;
this.tbUsername.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.appSettingsBindingSource, "Username", true));

Here's the line from the form's load method:

this.appSettingsTableAdapter.Fill(this.dSAppSettings.AppSettings, CompanyID);

Solution

  • Well, I've worked around the problem, but I'm sure I've missed some fundamental step that led to this problem in the first place.

    My bound controls are on two different tabs. So, I activated each tab and then set the focus to each control on the tab:

    // Workaround: Focus() forces the dataset value into the bound property of a control
    
    tabCtlSettings.SelectedTab = tabAccountSettings;  // Activate second tab
    foreach (Control ctl in tabAccountSettings.Controls)
      ctl.Focus();
    
    tabCtlSettings.SelectedTab = tabOptions;  // Activate first tab
    foreach (Control ctl in tabOptions.Controls)
        ctl.Focus();
    

    I know it's an awful band aid of a fix, but it'll have to do to get the project finished!