Search code examples
c#.netwinformstabcontroltabpage

How to close tab page on tabcontrol by tab page's name


In c# how can I destroy a tab on a tab control by targeting it's name? I've a tab named "Hello!" and I'd like to close it programatically. There's no guarantee that it will be the selected tab at the time.


Solution

  • The TabControl class provides a TabPages property that returns a TabPageCollection containing all of the TabPages in the control.

    So you can use the Item property to retrieve the TabPage with the specified name.

    For example, if the tab page you want is named "Hello!", you would write:

    var tabPage = myTabControl.TabPages["Hello!"];
    

    To remove the TabPage from the control, use the RemoveByKey method:

    myTabControl.TabPages.RemoveByKey("Hello!");
    

    Of course, in order for this to work, you'll need to make sure that you've set the keys of your TabPages to match the caption text they display.