用于动态创建文本框的 Textchanged 事件

发布于 2024-10-09 15:19:48 字数 613 浏览 3 评论 0原文

我有这样的问题: 有一些函数可以动态创建 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。我知道静态创建对象的解决方案,但动态创建的对象?几个小时我找不到解决方案。

任何帮助将不胜感激。

I have problem like this:
Have some function where I dynamically create TabPage object and textBox control on it.

   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. I have function which supports changing content of the TextBox control:

    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. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自此以后,行同陌路 2024-10-16 15:19:48
var box = (TextBox)sender;
var page = (TabPage)sender.Parent;
page.Text = box.Text;
var box = (TextBox)sender;
var page = (TabPage)sender.Parent;
page.Text = box.Text;
╰沐子 2024-10-16 15:19:48

要获取父 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 方法引用它。

To get the parent TabPage, you can walk up the control hierarchy until you find it:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文