Search code examples
c#winformstabcontroltabpage

C# Winforms TabControl elements reading as empty until TabPage selected


I have Winform app I am writing in C#. On my form, I have a TabControl with seven pages, each full of elements (TextBoxes and DropDownLists, primarily). I pull some information in with a DataReader, populate a DataTable, and use the elements' DataBindings.Add method to fill those elements with the current values.

The user is able to enter data into these elements, press "Save", and I then set the parameters of an UPDATE query using the elements' Text fields. For instance:

updateCommand.Parameters.Add("@CustomerName", SqlDbType.VarChar, 100).Value = CustomerName.Text;

The problem I have is that once I load the form, all of the elements are apparently considered empty until I select each tab manually. Thus, if I press "Save" immediately upon loading the form, all of the fields on the TabPages that I have not yet selected try to UPDATE with empty data (not nice). As I select each TabPage, those elements will now send their data along properly. For the time being, I've worked out a (very) ugly workaround where I programmatically select each TabPage when the data is populated for the first time, but that's an unacceptable long-term solution.

My question is, how can I get all of the elements on the TabPages to return their data properly before the user selects that TabPage?


Solution

  • ho is correct; the elements on a TabPage are not created until that TabPage is selected. I just added a loop upon form load that selects each TabPage and now it works fine.

    foreach (TabPage tp in tabControl1.TabPages)
    {
        tp.Show();
    }