如何为文本框的所有按键事件分配一个方法 [英] how to assign one method to all keypress event of textboxes

查看:116
本文介绍了如何为文本框的所有按键事件分配一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含30或40个texbox的表单我想验证它用户只输入文本框中的数字而不是字符。所以我已经制作了一个方法,将在文本框按键事件上调用,但问题是可以在文本框的每个按键事件上调用这个方法如何将此方法分配给所有文本框的按键事件?

i have a form which include 30 or 40 texboxes i want to validate it that user enter only number in text box not characters. so i have made a method which will be called on textbox key press event but the question it is possible to call this one method on every keypress event of textbox how can i assign this method to all textbox's keypress event?

推荐答案

首先,如果您在设计时选择希望为特定事件分配相同EventHandler的所有TextBox,然后打开Property Inspector(F4),则可以选择一个已定义的EventHandler,它将连接到(添加到调用列表)所有选定的TextBox。或者,如您所见,在此处的其他解决方案中,您可以在代码中添加EventHandler。



这是一个用于TextBox的KeyPress EventHandler的代码示例,用于约束从我过去使用过的键盘输入的文字;它将忽略Control-V(粘贴)等键盘组合:
First, if you select, at design-time, all the TextBoxes you wish to assign the same EventHandler to for a specific event, and then open the Property Inspector (F4), you can select an EventHandler you have defined, and it will be wired-up to (added to the invocation list) all the selected TextBoxes. Or, as you have seen, in the other solutions here, you can add the EventHandler in code.

Here's a code example of a KeyPress EventHandler for TextBox, for constraining text input from the keyboard I've used in the past; it will ignore keyboard combinations like Control-V (paste):
private const char chrDelete = (char) Keys.Delete;

private const char chrBackSpace = (char) Keys.Back;

private const char chrEnterReturn = (char)Keys.Enter;

private void DigitsOnlyTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    char currentKey = e.KeyChar;

    e.Handled = ! (Char.IsDigit(currentKey) || currentKey == chrDelete || currentKey == chrBackSpace || currentKey == chrEnterReturn);

    if (e.Handled) return;

    if (currentKey == chrEnterReturn)
    {
        // call code to handle Enter/Return Event
    }
}

要防止右键单击上下文出现的菜单将TextBox的'ShortcutsEnabled属性设置为'false:这是阻止用户将任何内容粘贴到TextBox中的便宜方式。



允许粘贴,但拦截粘贴事件并验证它...确保它的所有数字...在WinForms中很复杂,但可以完成。

To prevent the right-click Context Menu from appearing set the 'ShortcutsEnabled property of the TextBox to 'false: that's the "cheap" way to block the user pasting whatever into the TextBox.

To allow pasting, but intercept the paste event and validate it ... make sure it's all digits ... is complicated in WinForms, but can be done.


使用带有适当掩码的MaskedTextBox(你会必须查找数字表示。



另一种方法是创建自己的控件(NumericTextBox?),您将在其中执行所有验证和按键处理。然后你只需把你的NumericTextBox而不是普通的。







没有更简单的方法。如果你真的想根据你的问题处理每一个,你可以为每个控件都有一个处理函数,但你仍然需要附加事件。



你可以做对于窗体的控件集合上的每个循环以及每个TextBox添加事件...但是第一次需要非数字文本框时会遇到麻烦。



如果此解决方案有所帮助,请花些时间接受解决方案。谢谢。
Use MaskedTextBox with appropriate mask (you'll have to lookup number representations).

Another way to do this is to create your own control (NumericTextBox?) in which you will do all validation and keypress handling. Then you simply put your NumericTextBox instead of "normal" one.



There is no easier way. If you really want to handle each one as per your question you can have one handler function for every control, but you still have to attach the event.

You can do for each loop on controls collection of the form and for each TextBox add the event...but you'll run into trouble first time you need textbox that is NOT numeric.

If this solution helps, please take time to accept the solution. Thank you.


它不是assign。如果您有事件实例,则可以使用运算符+ =将事件处理程序添加到其调用列表中。例如:

It's not "assign". If you have an event instance, you can add an event handler to its invocation list, using the operator '+='. For example:
using System.Windows.Forms;

// ...

    void AddEventHandlers(TextBox[] allMyTextBoxes) {
        foreach (TextBox textBox in allMyTextBoxes)
            textBox.KeyPress += (sender, eventArgs) => {
                TextBox instance = (TextBox)sender; // in case you need to
                                                    // identify them
                char keyChar = eventArgs.KeyChar; // to know what's pressed :-)
                // if you want to cancel some key press, use:
                // eventArgs.Handled = true;
                // in your case:
                if (!(keyChar == (char)8) || char.IsDigit(keyChar))
                    eventArgs.Handled = true;
                // and so on... generally, do whatever you want:
                //DoSomethingWithEventThoseParameters(sender, keyChar);
                // or
                //DoSomethingElseWithEventArguments(eventArgs);
                // ...
            };
    }



重要提示:请注意,我也允许使用角色#8。这是退格。过滤输入时不要忘记它。



请参阅:

http://msdn.microsoft.com/en-us/library/system.windows.forms .control.keypress%28v = vs.110%29.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.windows.forms .keypresseventargs.handled%28v = vs.110%29.aspx [ ^ ]。



请注意,如果你想要要处理不是字符,而是使用键,你需要处理事件 KeyDown KeyUp



-SA


Important: note that I also allowed a character #8. This is backspace. Don't forget about it when filtering input.

Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled%28v=vs.110%29.aspx[^].

Note that if you want to deal not with characters, but with keys, you need to handle the events KeyDown or KeyUp.

—SA


这篇关于如何为文本框的所有按键事件分配一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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