Access controls from a Usercontrol that is programmatically added more than once?

非 Y 不嫁゛ 提交于 2019-12-10 10:39:33

问题


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.



来源:https://stackoverflow.com/questions/8003370/access-controls-from-a-usercontrol-that-is-programmatically-added-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!