[英]Textchanged event for dynamically create textbox
我遇到这样的问题:具有一些功能,可以在其中动态创建TabPage对象和textBox控件。
private void Create()
{
TabPage zakladkaTabControl = createTabPage();
TextBox TB = new TextBox();
TB.TextChanged += new EventHandler(TB_TextChanged);
}
现在,当我在TextBox控件中编写内容时,需要动态更改TabPage名称。 我有支持更改TextBox控件内容的函数:
private void textBox1_TextChanged(object sender, EventArgs e)
{
((TabPage)sender).Text = ((TextBox)sender).Text;
}
它不起作用,因为函数仅调用TextBox对象,而不调用TextBox和TabPage。 我知道静态创建但动态创建的对象的解决方案吗? 几个小时我找不到解决方案。
非常感激任何的帮助。
var box = (TextBox)sender;
var page = (TabPage)sender.Parent;
page.Text = box.Text;
要获取父级TabPage,可以遍历控件层次结构,直到找到它为止:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var tb = (TextBox)sender;
Control ctl = tb.Parent;
while (ctl != null && !(ctl is TabPage))
{
ctl = ctl.Parent;
}
if (parent != null)
{
var tp = (TabPage)parent;
// Change the TabPage name here
}
}
或者,可以将zakladkaTabControl设置为类的属性,而不是局部变量,以便可以从textBox1_TextChanged方法引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.