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

我想限制可以在文本框中输入的数字和字母。 假设我只想允许数字0-5和字母ad(包括小写和大写)。 我已经尝试过使用蒙面文本框,但它只允许我指定数字,仅限字母(两者都没有限制)或数字和字母,但按特定顺序排列。 最佳方案是:用户尝试输入数字6,并且没有任何内容输入到文本框中,对于范围af之外的字母也是如此。 我认为最好使用的事件是Keypress活动,但我不知道如何实现限制。

使用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; } } 

像这样覆盖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; } 

这将告诉textBox它将考虑哪些键作为用户输入。

使用KeyDown事件,如果e.Key不在允许的集合中,那么只需e.Handled = true

另一种方法是接受所有输入,validation它然后向用户提供有用的反馈,例如要求他们输入特定范围内的数据的错误标签。 我更喜欢这种方法,因为用户知道出了问题并且可以修复它。 它在Web表单的整个Web上使用,对于您的应用程序的用户来说并不奇怪。 按键并完全没有响应可能会令人困惑!

http://en.wikipedia.org/wiki/Principle_of_least_astonishment

Keypress活动可能是您最好的选择。 如果输入的char不是您想要的char,请检查那里,将e.SuppressKey设置为true以确保未触发KeyPress事件,并且不将char添加到文本框中。

如果您使用的是ASP.NET Web窗体,那么正则表达式validation将是最简单的。 在MVC中,像MaskedEdit这样的jQuery库是一个很好的起点。 上面的答案很好地记录了Windows表单方法。