user1224504
user1224504

Reputation: 1

Create an event for tab pages in C#

I am developing an application in C# Windows Forms, and I would like to create an event handler/event handlers based on whether or not a particular tab page of a tab control is selected. So for example, if I have three tab pages:

tabPage1,
tabPage2,
tabPage3,

which belong to

tabControl1,

I need the code to either:

  1. Have three separate event handlers for each tab page
  2. Have one event handler and inside of the event handler there is code which can determine the tab page that is currently selected (e.g. a case statement of some sort)

I have looked at several examples thus far, but none seem to do what I need. How can I create this event/ these events?

Upvotes: 0

Views: 9897

Answers (5)

mo.
mo.

Reputation: 3544

This was helping me out:

private void tabControl1_Selected(Object sender, TabControlEventArgs e)
{
    // Could be initialized in "Form_Load"
    var validTabPages = new[]
    {
        tabPage1,
        tabPage2,
        tabPage3,
        tabPage4
    };

    // If not a valid TabPage, just return
    if (!validTabPages.Contains(e.TabPage))
        return;

    pictureBox2.Parent.Controls.Remove(pictureBox2);
    pictureBox5.Parent.Controls.Remove(pictureBox5);

    e.TabPage.Controls.Add(pictureBox2);
    e.TabPage.Controls.Add(pictureBox5);
}

Upvotes: 0

Casperah
Casperah

Reputation: 4564

You should look for the VisibleChanged event on a child control of the tab page. This event will be fired for all the child controls in the tab page.

This is very useful when you place a CustomControl on each page. Then you can update the CustomControl when VisibleChanged is fired.

Upvotes: 0

Tigran
Tigran

Reputation: 62265

May be something like this:

Make use of TabControl.Selected

private void tabControl1_Selected(Object sender, TabControlEventArgs e) 
{

   if(e.TabPage == tabPage1) 
     DoSomethingInRelationOfTab1();
   else if(e.TabPage == tabPage2)
     DoSomethingInRelationOfTab2();
   ....
   ....
}

Upvotes: 4

mo.
mo.

Reputation: 3544

Another solution is to subclass TabPage

class MyTabPage : TabPage {
    event EventHandler Activated;

    public void OnActivated() {
        if (Activated != null)
           Activated(this, EventArgs.Empty);
    }
}

void HandleTabIndexChanged(object sender, EventArgs args) {
    var tabControl = sender as TabControl;
    var tabPage = tabControl.SelectedTab as MyTabPage;
    if (tabPage != null)
        tabPage.OnActivated();
}

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20640

Like this?

private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
    MessageBox.Show("Current Tab: " + tabControl1.SelectedTab.Text);
}

Upvotes: 1

Related Questions