Reputation: 69
I have the following code that creates a TabPage with Text tab1
:
string tabTitle = "tab1";
TabPage createdtabpage = new TabPage(tabTitle);
tabControl1.TabPages.Add(createdtabpage);
I want to get a TabPage using the string that I've set and then select it. Maybe something like this:
//this will select the tab that has a title of "tab1"
this.tabControl1.SelectedTab = tabControl1.getTabByTitle(tabTitle);
Is there a way to accomplish something like that?
Thanks for any help.
Upvotes: 1
Views: 763
Reputation: 32288
If you can assign the same value to the TabPage.Text
property and TabPage.Name
property, in case the assigned Text is compatible with Name property constraint (as it would be when the Text is "tab1"
, as shown in the question), then simply select the TabPage by its name:
string tabTitle = "tab1";
tabControl1.TabPages.Add(new TabPage(tabTitle));
// [...]
tabControl1.SelectedTab = tabControl1.TabPages[tabTitle];
If the Text is not compatible (as "This is TabPage1"
), then you can use LINQ's OfType() to select a TabPage that has the Text specified:
tabControl1.SelectedTab = tabControl1.TabPages.OfType<TabPage>()
.FirstOrDefault(tp => tp.Text == tabTitle);
In this case, if the TabPage is not found, FirstOrDefault() will return null
and the TabControl will show no TabPage selected in the UI.
Upvotes: 1