[英]Textchanged event for dynamically create textbox
I have problem like this: Have some function where I dynamically create TabPage object and textBox control on it. 我遇到这样的问题:具有一些功能,可以在其中动态创建TabPage对象和textBox控件。
private void Create()
{
TabPage zakladkaTabControl = createTabPage();
TextBox TB = new TextBox();
TB.TextChanged += new EventHandler(TB_TextChanged);
}
Now I need to change TabPage name dynamically when I write something in my TextBox control. 现在,当我在TextBox控件中编写内容时,需要动态更改TabPage名称。 I have function which supports changing content of the TextBox control:
我有支持更改TextBox控件内容的函数:
private void textBox1_TextChanged(object sender, EventArgs e)
{
((TabPage)sender).Text = ((TextBox)sender).Text;
}
It doesn't work because function calling only to the TextBox object and not the TextBox and TabPage. 它不起作用,因为函数仅调用TextBox对象,而不调用TextBox和TabPage。 I know a solution for objects created statically, but dynamically?
我知道静态创建但动态创建的对象的解决方案吗? For several hours I can not find a solution.
几个小时我找不到解决方案。
Any help would be most appreciated. 非常感激任何的帮助。
var box = (TextBox)sender;
var page = (TabPage)sender.Parent;
page.Text = box.Text;
To get the parent TabPage, you can walk up the control hierarchy until you find it: 要获取父级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
}
}
Alternatively, you could make zakladkaTabControl a property of the class rather than a local variable so that you can refer to it from the textBox1_TextChanged method. 或者,可以将zakladkaTabControl设置为类的属性,而不是局部变量,以便可以从textBox1_TextChanged方法引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.