从以编程方式添加多次的Usercontrol中访问控件? [英] Access controls from a Usercontrol that is programmatically added more than once?
问题描述
我搜索了很多东西,却找不到任何地方的帮助。
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;
}
因此,当我单击一个按钮时,说2或3次,怎么做我可以从该选项卡的userControl中的textBox中获取文本吗?
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?
推荐答案
您需要扩展TabPage并具有包含子对象的属性,例如:
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";
您还必须进入UserControl设计器文件,并将文本框声明从private更改为public。
You will also have to go into the UserControl designer file and change the textbox declaration from private to public.
这篇关于从以编程方式添加多次的Usercontrol中访问控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!