Ann*_*Bot 17 c# textbox winforms
我怎样才能只允许Visual C#文本框中的某些字符?用户应该能够将以下字符输入到文本框中,其他所有内容都应该被阻止:0-9,+, - ,/,*,(,).
我用Google来查找这个问题,但我得到的唯一解决方案是只允许使用字母字符,只允许数字或禁止使用某些字符.我想要的不是禁止某些字符,除了我在代码中添加的字符外,我想默认禁止所有内容.
Pau*_*bra 27
正如评论中提到的(以及我输入的另一个答案),您需要注册一个事件处理程序来捕获文本框上的keydown或keypress事件.这是因为TextChanged仅在TextBox失去焦点时触发
以下正则表达式允许您匹配您想要允许的字符
Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);
Run Code Online (Sandbox Code Playgroud)
而这恰恰相反,捕获了不允许的字符
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);
Run Code Online (Sandbox Code Playgroud)
我不假设有一个匹配,因为有人可以将文本粘贴到文本框中.在这种情况下catch textchanged
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0) {
//tell the user
}
}
Run Code Online (Sandbox Code Playgroud)
并验证单键按下
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for a naughty character in the KeyDown event.
if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
Ice*_*ind 10
您需要KeyDown
在文本框中订阅该事件.然后这样的事情:
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
&& e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*'
&& e.KeyChar != '/')
{
e.Handled = true;
return;
}
e.Handled=false;
return;
}
Run Code Online (Sandbox Code Playgroud)
重要的是要知道,如果你将Handled
属性更改为true
,它将不会处理击键.将其设置为false
将.
归档时间: |
|
查看次数: |
90178 次 |
最近记录: |