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

atwellpub picture atwellpub · Feb 17, 2012 · Viewed 9.4k times · Source

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.

Answer

Cody Gray picture Cody Gray · Feb 17, 2012

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.