I have a TabControl in a windows form. I have pragmaticly added new tabs like so:
for (int i = 1; i < numOfLanguages; i++)
{
// add a tab for each language
string tabTitle = split[i];
TabPage newTab = new TabPage(tabTitle);
languageTabs.TabPages.Add(newTab);
}
inside the loop I want to set up the other controlls for each tab. mainly I want to add buttons. I have seen this code:
tabPage1.Controls.Add(new Button());
Based off this example I want to do something similar like:
languageTabs.SelectTab(split[i]).Add(new Button());
I know that this code wont work. Have been looking through the params and cant see anything that lets me do this kind of thing.
Any ideas community?
SelectTab
moves the actual TabControl
to the specified tab, it does not return the tab to let you manipulate it.
You can index into the tab pages as follows:
languageTabs.TabPages[2].Controls.Add(new Button());
If you have set the Name
property on the TabPage
on creation, then you can also find individual tabs by key:
for (int i = 1; i < numOfLanguages; i++)
{
// add a tab for each language
string tabTitle = split[i];
TabPage newTab = new TabPage(tabTitle);
newTab.Name = tabTitle;
languageTabs.TabPages.Add(newTab);
}
...
languageTabs.TabPages[split[i]].Controls.Add(new Button());
(See MSDN for more)
Whichever is most convenient.
LINQ?
languageTabs.TabPages.First(tab => tab.Title == split[i]).Add(new Button());
This might be not reliable (crash) if your tabcontrol does not have tab with specific name, so you might want more reliable way:
if (languageTabs.TabPages.Exists(tab => tab.Title == split[i]))
{
languageTabs.TabPages.First(tab => tab.Title == split[i]).Add(new Button());
}
来源:https://stackoverflow.com/questions/8309188/adding-buttons-to-a-tabcontrol-tab-in-c-sharp