Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Select a TabPage by its Label/Text

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.

question from:https://stackoverflow.com/questions/66052316/select-a-tabpage-by-its-label-text

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...