Access controls from a Usercontrol that is program

2019-05-27 06:08发布

问题:

Well I've search a lot, and can't find help anywhere.

I have a form with tabs. When I click a button, a new tab is added, and a usercontrol is added to the new tab.

I cannot figure out how to access the controls on the second + tabs. I can access the user controls just fine from the first tab.. just not the others.

Here is the code I had so far.

private void button1_Click(object sender, EventArgs e)
{
    string title = "tabPage " + (tabControl1.TabCount + 1).ToString();
    TabPage newPage = new TabPage(title);
    tabControl1.TabPages.Add(newPage);

    UserControl1 newTabControl = new UserControl1();
    newPage.Controls.Add(newTabControl);
}

private void button2_Click(object sender, EventArgs e)
{
    label1.Text = userControl1.textBox1.Text;
}

So when I click button one, say 2 or 3 times, and how do I get the text from the textBox in the userControl from that tab?

...maybe I'm going about it all wrong?

回答1:

You need to extend the TabPage and have properties that contain the child objects, for example:

public class ExtendedTabPage : TabPage
{
    public UserControl1 UserControl { get; private set; }

    public ExtendedTabPage(UserControl1 userControl)
    {
        UserControl = userControl;
        this.Controls.Add(userControl);
    }
}

Then you can access it via .UserControl as long as you still have a reference to it.. like so:

ExtendedTabPage newTab = new ExtendedTabPage(new UserControl1());
tabControl1.TabPages.Add(newTab);

newTab.UserControl.textBox1.Text = "New Tab User Control TextBox";

You will also have to go into the UserControl designer file and change the textbox declaration from private to public.