将事件 TextChanged 分配给表单中的所有文本框

Assigning event TextChanged to all textboxes in Form(将事件 TextChanged 分配给表单中的所有文本框)
本文介绍了将事件 TextChanged 分配给表单中的所有文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想知道如何查看 Form 中的所有 textboxes 是否有任何更改值.我看到了一些代码 这里

Hello I was wondering how can I keep an eye on all textboxes in Form whether in any of them was changed value. I saw some code here

private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control ctrl in this.Controls)
    {
        if (ctrl is TextBox)
        {
            TextBox tb = (TextBox)ctrl;
            tb.TextChanged += new EventHandler(tb_TextChanged);
        }
    }
}

void tb_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    tb.Tag = "CHANGED"; // or whatever
}

编写此代码的人说它不能分配给 Panels 和 Grouboxes 中的文本框".

And a guy who wrote this code says that "it can't be assigned to textboxes in Panels and Grouboxes".

所以我的问题是,因为我在组框或面板中几乎有每个文本框,我如何才能查看是否对面板或组框中的文本框进行了更改?

So my question is as I have almost every textbox in groubox or panel, how can I see whether change was made for textboxes in panels or groupbox?

推荐答案

你可以让你的方法递归:

You can make your method recursive:

private void Form1_Load(object sender, EventArgs e)
{
    Assign(this);
}

void Assign(Control control)
{
    foreach (Control ctrl in control.Controls)
    {
        if (ctrl is TextBox)
        {
            TextBox tb = (TextBox)ctrl;
            tb.TextChanged += new EventHandler(tb_TextChanged);
        }
        else
        {
            Assign(ctrl);
        }
    }
}

void tb_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    tb.Tag = "CHANGED"; // or whatever
}

只需为方法找到一个更好的名称,而不是 Assign.

Just find a better name for the method instead of Assign.

这篇关于将事件 TextChanged 分配给表单中的所有文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)