Search code examples
c#winformsuser-controlstabcontrol

WinForms on Tabpage selected run method in UserControl


My Tabcontrol has 3 Tabpages. I am currently in Tabpage 1, when I would select Tabpage 2. I want to run a method in my UserControl assigned to that Tabpage. You could call this a "Focus" listener. How would I implement this? Or is this possible at all?

Edit:

Lets say I have a file named "UserControl1.cs" In here there is a method OnFocus() I would like to call this method when its Tabpage becomes the active tab. I am assigning the UserControl to the Tabpage like this:

        // AllOpenUserControls = List<UserControl> // With the active pages

        TabPage newPage = new TabPage();
        newPage.Text = title;
        newPage.AutoScroll = true;
        newPage.BackColor = SystemColors.Window;
        newPage.Controls.Add(userControl);
        AllOpenUserControls.Add(userControl);

        tabControl.TabPages.Add(newPage);

Solution

  • Add the EventHandler for SelectedIndexChanged here:

    ...
    tabControl.TabPages.Add(newPage);
    tabControl.SelectedIndexChanged += new EventHandler(userControl.OnFocus);
    

    Your OnFocus-method should look like this:

    public void OnFocus(object sender, System.EventArgs e)
    {
        TabControl tc = (TabControl)sender;
        if (tc.SelectedTab == this.Parent)
        {
            //Parent-Tab is selected, do stuff...
        }
    }