简体   繁体   English

限制文本框中的数字和字母-C#

[英]Restrict numbers and letters in textbox - C#

I want to restrict what numbers and letters can be entered into a textbox. 我想限制可以在文本框中输入的数字和字母。 Let's say I only want to allow numbers 0-5 and letters ad (both lower and uppercase). 假设我只想允许数字0-5和字母ad(小写和大写)。 I already tried using a masked text box but it only let me specify numbers only, letters only (both without restriction) or numbers and letters together but in a particular order. 我已经尝试过使用带遮罩的文本框,但是它只允许我仅指定数字,仅指定字母(均无限制)或同时指定数字和字母,但顺序相同。 Best scenario would be: user tries to enter number 6 and nothing gets entered into the textbox, same for letters outside the range af. 最好的情况是:用户尝试输入数字6,但没有任何内容输入文本框,对于af范围以外的字母也是如此。 I think the best event to use would be the Keypress event, but I am at a loss as to how I can achieve the restriction thing. 我认为最好使用的事件将是Keypress事件,但是我对如何实现限制事情一无所知。

Use the KeyPress Event for your textbox. 为您的文本框使用KeyPress事件。

protected void myTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs)
{
    e.Handled = !IsValidCharacter(e.KeyChar);
}

private bool IsValidCharacter(char c)
{
    bool isValid = true;

    // put your logic here to define which characters are valid
    return isValid;
}
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}

Override the PreviewKeyDownEvent like this: 像这样重写PreviewKeyDownEvent:

    private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.A || e.KeyCode == Keys.B || ...)
            e.IsInputKey = true;
        else
            e.IsInputKey = false;
    }

This will tell the textBox which keys it will consider as a user input or not. 这将告诉textBox将其视为用户输入的键。

Use the KeyDown event and if the e.Key is not in your allowable set, then just e.Handled = true . 使用KeyDown事件,如果e.Key不在允许的范围内,则只需e.Handled = true

An alternative would be accept all input, validate it and then provide useful feedback to the user, for example an error label asking them to enter data within a certain range. 一种替代方法是接受所有输入,对其进行验证,然后向用户提供有用的反馈,例如,错误标签要求用户输入一定范围内的数据。 I prefer this method as the user knows something went wrong and can fix it. 我更喜欢这种方法,因为用户知道出了点问题并可以解决。 It is used throughout the web on web forms and would be not at all surprising for a user of your app. 它在Web表单上的整个Web上使用,对于您的应用程序用户来说一点也不奇怪。 Pressing a key and getting no response at all might be confusing! 按下一个键,根本没有任何反应可能会造成混淆!

http://en.wikipedia.org/wiki/Principle_of_least_astonishment http://en.wikipedia.org/wiki/基本原理

The Keypress event is probably your best bet. Keypress事件可能是您最好的选择。 Do a check there if the entered char is not the char you want, set e.SuppressKey to true to make sure the KeyPress event is not fired, and the char is not added to the textbox. 如果输入的字符不是您想要的字符,请在e.SuppressKey进行检查,将e.SuppressKey设置为true ,以确保不会触发KeyPress事件,并且该字符未添加到文本框中。

If you are using ASP.NET Web Forms a regular expression validation would be the easiest. 如果您使用的是ASP.NET Web窗体,则最容易进行正则表达式验证。 In MVC, a jQuery library such as MaskedEdit would be a good place to start. 在MVC中,像MaskedEdit这样的jQuery库将是一个不错的起点。 The answers above document the Windows forms approach well. 上面的答案记录了Windows窗体的处理方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM