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.
Asked
Active
Viewed 9,645 times
2 Answers
4
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 TabPage
s to match the caption text they display.

Cody Gray - on strike
- 239,200
- 50
- 490
- 574
-
that was quick, beat me to it! – sambomartin Feb 17 '12 at 22:30
-
Thank you Cody! Looking at LarsTech's answer, should I dispose it instead of remove it for memory's sake? – atwellpub Feb 17 '12 at 22:44
-
@atw I would do both, just to be on the safe side. Remove it first, then dispose it. But you can get away with just disposing it ([reference](http://stackoverflow.com/questions/1757116/remove-tabpage-dispose-or-clear-or-both)). – Cody Gray - on strike Feb 17 '12 at 22:44
-
I've setup the solution but am setback: 'System.Windows.Forms.TabControl.TabPageCollection' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Windows.Forms.TabControl.TabPageCollection' could be found (are you missing a using directive or an assembly reference?) – atwellpub Feb 17 '12 at 22:49
-
@atw Hmm, yeah `Item` is the default property in C#. My syntax is wrong. I've spent too long today looking at VB.NET code. – Cody Gray - on strike Feb 17 '12 at 22:57
2
You can try something like this:
for (int i = tabControl1.TabPages.Count - 1; i >= 0; i--) {
if (tabControl1.TabPages[i].Text == "Hello!")
tabControl1.TabPages[i].Dispose();
}
I'm assuming you meant the "Text" of the TabPage, since "Hello!" wouldn't be a valid name for a control.
Note: this code will dispose of any TabPage that says "Hello!"

LarsTech
- 80,625
- 14
- 153
- 225
-
Is disposing a tabpage while it's still added to a tabcontrol a good idea? – Blorgbeard Feb 17 '12 at 22:30
-
@Blorgbeard I don't think there is any danger. Removing it doesn't dispose of it, and the OP said he wanted it "destroyed". – LarsTech Feb 17 '12 at 22:33
-
1@sambomartin Dispose() will remove it. See [Hans Passant answer here](http://stackoverflow.com/a/1970158/719186). – LarsTech Feb 17 '12 at 22:39
-
The clearer and more definitive answer to that question is [here](http://stackoverflow.com/questions/1757116/remove-tabpage-dispose-or-clear-or-both). – Cody Gray - on strike Feb 17 '12 at 22:46