C# TabControl Selected event seems to not work

Windex picture Windex · Dec 31, 2011 · Viewed 14.2k times · Source

I am trying to access the event handler for selecting a tab, basically I have 3 tab pages inside of tabControl1. I want to be able to manipulate what is displaying in a listbox based on what tab is selected at the moment as a new tab is selected. This does not work, anytime a tab page is selected it fails to show the message box, (when that line is uncommented)

private void tabControl1_Selected(Object sender, EventArgs e)
{
    //MessageBox.Show(tabControl1.SelectedIndex.ToString());3

    if (tabControl1.SelectedIndex == 0)
    {
        //do something
    }
}

Answer

LarsTech picture LarsTech · Dec 31, 2011

That is not the right assignment. Your second parameter is wrong.

Try this:

private void tabControl1_Selected(object sender, TabControlEventArgs e) {
  if (e.TabPage.Name == tabPage1.Name)
    MessageBox.Show("First Tab!");
}

And make sure you have it wired up correctly (it sounds like you don't have the event actually handled):

public Form1() {
  InitializeComponent();

  tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
}