C# 如何使文本框只接受字母字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/790378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:15:20  来源:igfitidea点击:

How to make Textbox only accept alphabetic characters

c#winforms

提问by Sohail Anwar

I have a windows forms app with a maskedtextboxcontrol that I want to only accept alphabetic values in.

我有一个带有maskedtextbox控件的 Windows 窗体应用程序,我只想接受其中的字母值。

Ideally, this would behave such that pressing any other keys than alphabetic keys would either produce no result or immediately provide the user with feedback about the invalid character.

理想情况下,这会导致按下字母键以外的任何其他键不会产生任何结果或立即向用户提供有关无效字符的反馈。

采纳答案by TheTXI

From MSDN(This code shows how to handle the KeyDown event to check for the character that is entered. In this example it is checking for only numerical input. You could modify it so that it would work for alphabetical input instead of numerical):

来自MSDN(此代码显示了如何处理 KeyDown 以检查输入的字符。在此示例中,它仅检查数字输入。您可以对其进行修改,使其适用于字母输入而不是数字):

// 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;
    }
}

回答by Fredrik M?rk

This code will distinguish alphabetic character key presses from non alphabetic ones:

此代码将区分字母字符按键和非字母按键:

private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Regex.IsMatch(e.KeyChar.ToString(), @"\p{L}"))
    {
        // this is a letter
    }
    else
    {
        // this is NOT a letter
    }
}

Update: note that the above regex pattern will match ONLY alphabetic characters, so it will not allow spaces, commas, dots and so on. In order to allow more kinds of characters, you will need to add those to the pattern:

更新:请注意,上面的正则表达式模式将仅匹配字母字符,因此不允许使用空格、逗号、点等。为了允许更多种类的字符,您需要将它们添加到模式中:

// allow alphabetic characters, dots, commas, semicolon, colon 
// and whitespace characters
if (Regex.IsMatch(e.KeyChar.ToString(), @"[\p{L}\.,;:\s]"))

回答by Cerebrus

This question has probably been asked and answered a million times on every conceivable programming forum. Every answer provided has the distinction of being unique to the stated requirements.

这个问题可能已经在每个可以想象的编程论坛上被问到和回答了一百万次。所提供的每个答案都具有独特于所述要求的区别。

Since you are using a MaskedTextBox, you have additional validation features available to you and do not really need to handle keypresses. You can simply set the Mask property to something like "L" (character required) or "?" (optional characters). In order to show feedback to the user that the input is not acceptable, you can use the BeepOnErrorproperty or add a Tooltip to show the error message. This feedback mechanism should be implemented in the MaskedInputRejectedevent handler.

由于您使用的是MaskedTextBox,因此您可以使用其他验证功能,并且实际上不需要处理按键。您可以简单地将 Mask 属性设置为“L”(需要字符)或“?” (可选字符)。为了向用户显示输入不可接受的反馈,您可以使用该BeepOnError属性或添加工具提示来显示错误消息。这种反馈机制应该在MaskedInputRejected处理程序中实现。

The MaskedTextBoxcontrol offers a ValidatingTypeproperty to check input that passes the requirements of the Mask, but may not be the correct datatype. The TypeValidationCompletedevent is raised after this type validation and you can handle it to determine results.

MaskedTextBox控件提供了一个ValidatingType属性来检查通过掩码要求的输入,但可能不是正确的数据类型。该TypeValidationCompleted在此类型验证后引发,您可以对其进行处理以确定结果。

If you still need to handle keypress events, then read on...!

如果您仍然需要处理按键,请继续阅读...!

The method I would recommend in your case is that instead of handling the KeyDownevent (you ostensibly do not need advanced key handling capability) or using a Regex to match input (frankly, overkill), I would simply use the built-in properties of the Char structure.

在您的情况下,我建议的方是,我不会处理KeyDown(您表面上不需要高级密钥处理功能)或使用正则表达式来匹配输入(坦率地说,矫枉过正),我只会使用内置属性字符结构。

private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  Char pressedKey = e.KeyChar;
  if (Char.IsLetter(pressedKey) || Char.IsSeparator(pressedKey) || Char.IsPunctuation(pressedKey))
  {
    // Allow input.
    e.Handled = false
  }
  else
    // Stop the character from being entered into the control since not a letter, nor punctuation, nor a space.
    e.Handled = true;
  }
}

Note that this snippet allows you to handle punctutation and separator keys as well.

请注意,此代码段还允许您处理标点符号和分隔符键。

回答by sivakumar siddam

// This is  to allow only numbers.
// This Event Trigger, When key press event occures ,and it only allows the Number and Controls., 
private void txtEmpExp_KeyPress(object sender, KeyPressEventArgs e)
{
    if(Char.IsControl(e.KeyChar)!=true&&Char.IsNumber(e.KeyChar)==false)
    {
        e.Handled = true;
    }
}

//At key press event it will allows only the Characters and Controls.
private void txtEmpLocation_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) == true)
    {
        e.Handled = true;
    }
}

回答by Mahir

//Add a text box select it & goto Events & In the event list double click on "keypress" event.

//添加一个文本框选择它并转到 & 在列表中双击“keypress”。

        if (!char.IsLetter(e.KeyChar))
        {
            MessageBox.Show("Enter only characters");
        }
    }

回答by Aarón Iba?ez Wertherm?nn

This works for me :)

这对我有用:)

    private void txt_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !((e.KeyChar != '?' && e.KeyChar != '?') && char.IsLetter(e.KeyChar));
    }

回答by user4340666

Try thiscode

试试这个代码

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
    }