atwellpub
atwellpub

Reputation: 6010

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.

Upvotes: 2

Views: 9797

Answers (2)

Cody Gray
Cody Gray

Reputation: 244722

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.

Upvotes: 4

LarsTech
LarsTech

Reputation: 81610

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!"

Upvotes: 2

Related Questions