[SOLVED]处理表单中所有文本框的事件 [英] [SOLVED]Handle events for all textboxes in a form
问题描述
您好Evereyone,我有一个小问题:
我有一个包含十个文本框的表单,我想用一种方法处理所有文本框的onKeyPress事件,而无需为每个文本框编写一个方法.
示例:
我不想有这样的东西:
Hi evereyone, i have a little question:
I have a form with ten textboxes and i want to handle the onKeyPress events for all the textboxes in just one method without need to write one method for every textbox.
Example:
I don''t want to have something like this:
private void textBox01_OnKeyPress() {}
private void textBox02_OnKeyPress() {}
private void textBox03_OnKeyPress() {}
........
private void textBox10_OnKeyPress() {}
我需要这样的东西:
I need something like this:
private void allTextBoxes_OnKeyPress() {}
仅需一个方法即可控制所有TextBoxes的OnKeyPress事件.
我该怎么办?
有可能吗?
提前谢谢.
最好的问候.
With just a single method control the OnKeyPress event of all TextBoxes.
How can i do this?
It is possible?
Thanks in advance.
Best Regards.
推荐答案
您可以这样做:
You can do it like this:
TextBox textBox = null;
foreach (Control control in this.Controls)
{
if ((textBox = control as TextBox) != null)
{
textBox.KeyPress += new KeyPressEventHandler(textBox_KeyPress);
}
}
正如d @ nish所说的那样,您可以使用他的代码以编程方式进行操作.
要使用设计器执行相同的操作,只需选择Form
上的所有TextBoxes
,在属性"窗口中选择事件"选项卡,选择KeyPress
项,然后选择以下任一项:键入要使用的名称,然后点击Return或双击它以使用默认方法名称(警告将使用您选择的第一个文本框的名称,例如textBox1_KeyPress(....)
).
As d@nish has said you can do it programmatically using his code.
To do the same thing using the designer simply select all theTextBoxes
on yourForm
, select the Events tab on the Properties Window, select theKeyPress
item and either: type in a name that you want to use and then hit Return, or double click it to use the default method name (warning this will use the name of the first TextBox you selected e.g.textBox1_KeyPress(....)
).
因此,只需为每个TextBox
的OnKeyPress
事件分配相同的事件处理程序方法.
编辑==============
根据您的评论,以上内容正是您想要的.创建单个处理程序:
So just assign the same event handler method to theOnKeyPress
event for eachTextBox
.
EDIT ==============
In response to your comment, the above is EXACTLY what you want. Create a single handler:
private void allTextBoxesKeyPress(...)
并对所有文本框控件使用THAT处理程序.
and use THAT handler for ALL of the text box controls.
这篇关于[SOLVED]处理表单中所有文本框的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!