如何将表单上的所有文本框控件与相同的事件处理程序相关联 [英] How to associate all textbox controls on a form with the same event handler

查看:34
本文介绍了如何将表单上的所有文本框控件与相同的事件处理程序相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

VB 2008.

我在一个表单上有几个文本框,我希望每个文本框都使用相同的事件处理程序.我知道如何手动将每一个连接到处理程序,但我正在寻找一种更通用的方法,因此如果我添加更多文本框,它们将自动连接到事件处理程序.

I have several text boxes on a form and I want each of them to use the same event handler. I know how to manually wire each one up to the handler, but I'm looking for a more generic way so if I add more text boxes they will automatically be hooked up to the event handler.

想法?

使用来自 MusiGenesis 的 C# 示例(并在 nick 留下的评论的帮助下),我编写了此 VB 代码:

Using the C# sample from MusiGenesis (and with the help of the comment left by nick), I wrote this VB code:

Private Sub AssociateTextboxEventHandler()
  For Each c As Control In Me.Controls
    If TypeOf c Is TextBox Then
      AddHandler c.TextChanged, AddressOf tb_TextChanged
    End If
  Next
End Sub

非常感谢!太好了.

推荐答案

在表单的加载事件中做这样的事情(C#,抱歉,但很容易翻译):

Do something like this in your form's load event (C#, sorry, but it's easy to translate):

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
}

它不是正确的递归(例如,它不会在面板上找到文本框),但您明白了.

It's not properly recursive (it won't find text boxes on panels, for example), but you get the idea.

这篇关于如何将表单上的所有文本框控件与相同的事件处理程序相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆