【发布时间】:2018-05-02 16:45:14
【问题描述】:
我正在处理昵称(给定名称)。
用户注册时,你必须输入你的昵称,同样,它不能包含符号(下划线除外),只能包含数字和字母。
我为此使用TextBox 用户名的KeyPress 事件:
private bool Handled = false;
private void Username_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetterOrDigit(e.KeyChar)) this.Handled = false;
else
{
if (e.KeyChar == '\b') this.Handled = false; //Backspace key
else
{
if (e.KeyChar == '_' && !((TextBox)sender).Text.Contains("_") && ((TextBox)sender).Text.Length > 0) this.Handled = false;
else this.Handled = true;
}
}
e.Handled = Handled;
}
这段代码防止那些符号(不同于“_”),内容以“_”开头,并使用多个下划线“H_E_L_L_O”写,但他们需要防止下划线可以在末尾使用,我的意思是:
允许:Hell_o
防止:你好_
这可能吗?
编辑:
我也使用了
String.Last(),但是结果是一样的:
if(TextBox.Text.Last() == '_')
{
// Handled = true;
}
【问题讨论】:
-
您可以编写一个以字符串 char 结尾的正则表达式。
-
在
if子句中比较SelectionStart和TextLength不能解决问题吗? -
this.Handled = false?那不是e.Handled吗? -
这是什么意思:"并且在"H_E_L_L_O"下使用了多个脚本"?
-
@LarsTech Handled 是一个私有布尔值
标签: c# string winforms textbox