本文介绍了使用一个声明管理所有已更改文本的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多文本框,现在我想将所有textChanged事件绑定到一个
事件处理程序,是否可以声明一个对象来处理所有textChanged事件?
我的意思是这样的:

I have many textbox ,now I want to bind all textChanged events to one
event handler ,is it possible to declare an object to handle all textChanged events?
I mean something like this :

(TextBox).TextChanged += new EventHandler(txt_TextChanged);





请告诉我如何?





please tell me HOW?

推荐答案

TextBox1.TextChanged += new EventHandler(txt_TextChanged);
TextBox2.TextChanged += new EventHandler(txt_TextChanged);
TextBox3.TextChanged += new EventHandler(txt_TextChanged);



上面的代码显示了3个文本框(TextBox1,TextBox2,TextBox3)如何具有相同的事件处理程序方法(txt_TextChanged).

希望有帮助,

谢谢,
Arindam D Tewary



Above code shows how 3 textbox(TextBox1,TextBox2,TextBox3) having same event handler method (txt_TextChanged).

Hope that helps,

Thanks,
Arindam D Tewary


void txt_TextChanged(object sender, EventArgs e)
{
    //This becomes a reference to the TextBox that raised the TextChanged event
    TextBox textBox = sender as TextBox;

}



如果要使用单独的类来处理所有TextChanged事件,也可以这样做.
如果您创建如下所示的类(请记住将using System.Windows.Forms;添加到该类中);



If you want to use a separate class to process all TextChanged events you can also do that.
If you create a class like the following (remember to add using System.Windows.Forms; to the class);

public class TextChangeHandler
{
    public void TextChanged(object sender, EventArgs e)
    {
        //This becomes a reference to the TextBox that raised the TextChanged event
        TextBox textBox = sender as TextBox;
    }
}


然后,您可以使用以下代码来处理TextChanged事件;


you can then use the following to handle the TextChanged event;

//This needs to be global for the form
TextChangeHandler txtChangeHandler = new TextChangeHandler();

//These go in the form constructor
textBox1.TextChanged += new EventHandler(txtChangeHandler.TextChanged);
textBox2.TextChanged += new EventHandler(txtChangeHandler.TextChanged);
textBox3.TextChanged += new EventHandler(txtChangeHandler.TextChanged);



您还可以将类设为静态并使用;



You can also make the class static and use;

public static class TextChangeHandler
{
    public static void TextChanged(object sender, EventArgs e)
    {
        //This becomes a reference to the TextBox that raised the TextChanged event
        TextBox textBox = sender as TextBox;
    }
}


然后,您可以使用以下代码来处理TextChanged事件;


you can then use the following to handle the TextChanged event;

textBox1.TextChanged += new EventHandler(TextChangeHandler.TextChanged);
textBox2.TextChanged += new EventHandler(TextChangeHandler.TextChanged);
textBox3.TextChanged += new EventHandler(TextChangeHandler.TextChanged);


foreach (Control c in this.Controls)
{
    ((TextBox)c).TextChanged += new EventHandler(Form1_TextChanged);
}


这篇关于使用一个声明管理所有已更改文本的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 08:53