Search code examples
c#winformscomboboxtabcontroltabpage

Changing text of a combobox in a different tab


I have a combo box which I need to mirror in another tab page in a C# winforms based application.

I have perfectly working code for when you select a different item from the drop down list. Unfortunately, however, when I change the Text of a tab that has not been clicked on yet nothing actually happens.

If I first click each tab then everything works as expected.

Now I'm putting this down to some form of lack of initialisation happening first. So I've tried to select each tab in my constructor.

tabControlDataSource.SelectedIndex = 0;
tabControlDataSource.SelectedIndex = 1;
// etc

But this doesn't work.

I've also tried calling tabControlDataSource.SelectTab( 1 ) and still it doesn't work.

Does anyone know how I can force the tab to "initialise"?


Solution

  • Ok, typically I post the question after struggling for an hour and shortly afterwards find the solution.

    TabPages are lazily initialised. So they don't fully initialise until they are made visible for the first time.

    So i added this code to my constructor:

            tabControlDataSource.TabPages[0].Show();
            tabControlDataSource.TabPages[1].Show();
            tabControlDataSource.TabPages[2].Show();
    

    but this didn't work :(

    It occurred to me, however, that the constructor might not be the best place. So I created an event handler for Shown as follows:

        private void MainForm_Shown( object sender, EventArgs e )
        {
            tabControlDataSource.TabPages[0].Show();
            tabControlDataSource.TabPages[1].Show();
            tabControlDataSource.TabPages[2].Show();
        }
    

    And now everything is working!