TabControl, the SelectedIndexChanged event and the current TabPage

by Codewiz51 May 27, 2010 22:08

I've seen a lot of new programmer questions regarding TabControls and how to determine which TabPage the user is viewing.  The following is a simple c# example to get a reference to the current TapPage using the SelectedIndexChanged event of the tab control.

// Make sure to reference the event handling code

this.tabMyTabControl.SelectedIndexChanged +=
    new System.EventHandler(this.tabMyTabControl_SelectedIndexChanged);

....

private void tabMyTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
    // Use this cast to get a reference to the parent TabControl
    // or simply reference the control directly

    TabControl tc = (TabControl)sender;
    string s = tc.Name;

    // Method 1.
    // Use the SelectedIndex property to get a reference to
    // the TabPage using the TabPages collection
    // You should check that SelctedIndex is not -1!

    TabPage tp = tc.TabPages[tc.SelectedIndex];
    s = tp.Name;
   
    // Method 2
    // Use the SelectedTab property to get a reference to
    // the current TabPage
    // I also illustrate how to access the TabControl directly,
    // rather than using a cast of the sender argument

    tp = this.tabMyTabControl.SelectedTab;
    s = tp.Name;
}

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Mooglegiant

Disclaimer

This blog represents my personal hobby, observations and views. It does not represent the views of my employer, clients, especially my wife, children, in-laws, clergy, the dog, the cats or my daughter's horse. In fact, I am not even sure it represents my views when I take the time to reread postings.

© Copyright 2008-2011