Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hello CPs,

I have created tabs dynamically inside a TabControl using the following code.

C#
string title = "TabPage " + (tabControl1.TabCount + 1).ToString();
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(new BrowserTab());


where BrowserTab is a class created using

C#
public class BrowserTab : TabPage
    {
        WebBrowser wb = new WebBrowser();
        public BrowserTab()
        {
            wb.Dock = DockStyle.Fill;
            this.Controls.Add(wb);
        }
    }


How can I access the newly created webbrowser control inside the dynamically created tab?
Posted
Updated 23-Aug-15 2:31am
v2

1 solution

for the TabControl use this:

C#
TabPage myTabPage = new TabPage(title);
myTabPage.Name = "tab" + tabControl1.TabCount;
tabControl1.TabPages.Add(new BrowserTab());


While inside the BrowserTab class you can use:

C#
public class BrowserTab : TabPage
{
    public WebBrowser Browser { get; private set; }
    public BrowserTab()
    {
        Browser = new WebBrowser();
        Browser.Dock = DockStyle.Fill;
        this.Controls.Add(Browser);
    }
}


So you can just do:
C#
var tab = tabControl1.TabPages.OfType<browsertab>().FirstOrDefault(t => t.Name == "tab5");
if(tab != null)
    tab.Browser.Refresh();
 
Share this answer
 
v3
Comments
Ashwin2013 23-Aug-15 9:19am    
Another sub question: after creating that method how to call Browser.DocumentCompleted for that tab;
Can something like this be done?
tab.Browser.DocumentCompleted() {
MessageBox.Show("Content Loaded");
}
Alberto Nuti 23-Aug-15 12:43pm    
I prefer the solution you have proposed, but you can also expose the event like this:
<pre lang="c#">
public class BrowserTab : TabPage
{
public event WebBrowserDocumentCompletedEventHandler DocumentCompleted;
public WebBrowser Browser { get; private set; }
public BrowserTab()
{
Browser = new WebBrowser();
Browser.DocumentCompleted += (snd, evt) => { if (DocumentCompleted != null) DocumentCompleted(snd, evt); };
Browser.Dock = DockStyle.Fill;
this.Controls.Add(Browser);
}
}
</pre>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900