限制文本框中的数字和字母 - C# [英] Restrict numbers and letters in textbox - C#
问题描述
我想限制可以在文本框中输入的数字和字母.假设我只想允许数字 0-5 和字母 a-d(小写和大写).我已经尝试过使用屏蔽文本框,但它只允许我指定数字、字母(均无限制)或数字和字母一起但按特定顺序指定.最好的情况是:用户尝试输入数字 6,但文本框中没有输入任何内容,对于 a-f 范围之外的字母也是如此.我认为最好使用的事件是 Keypress 事件,但我不知道如何实现限制.
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 a-d (both lower and uppercase). 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 a-f. 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.
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;
}
这篇关于限制文本框中的数字和字母 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!