Reputation: 217
I have a class called MainAreaTab which inherits from UserControl.
In a different user control (called Page3), I have a TabControl which contains TabPages, and every TabPages contains a MainAreaTab. This is the code where I do this and it works fine:
string mainAreaString = mData.GetMainAreaName((UInt32)mainAreaId);
MainAreaTab myUserControl = new MainAreaTab(mData, (uint)mainAreaId);
TabPage mainAreaTabPage = new TabPage(mainAreaString);//Create new tabpage
mainAreaTabPage.Controls.Add(myUserControl);
mTabControl.TabPages.Add(mainAreaTabPage);
As I said, this work fine. The problem comes when I want to access a public method of every MainAreaTab in every TabPage. I tried something like this but it does´t work:
foreach (TabPage tabPage in mTabControl.TabPages)
{
TabControl userControl = (TabControl)tabPage.Controls[0];
MainAreaTab tab = userControl as MainAreaTab;
}
The error I get is:
Cannot convert type 'System.Windows.Forms.TabControl' to 'MainAreaTab' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.
Am I missing something? Can this be done? Thanks in advance.
Upvotes: 1
Views: 843
Reputation: 66439
Another option is to use LINQ to grab all MainAreaTab
controls from all TabPage
's in one go.
var mainAreaTabs = mTabControl.TabPages.Cast<TabPage>()
.SelectMany(pg => pg.Controls.OfType<MainAreaTab>());
Then loop through the collection like this:
foreach (var tab in mainAreaTabs)
tab.SomeMethod();
Upvotes: 4
Reputation: 4006
Looking at your code, I believe you want to try the following:
foreach (TabPage tabPage in mTabControl.TabPages)
{
MainAreaTab tab = tabPage.Controls[0] as MainAreaTab;
}
What this does is:
foreach TabPage in TabControl
get the TabPage's MainAreaTab
Upvotes: 2