防止在要添加的文本框内容末尾添加下划线“_”
Prevent an underscore "_" at the end of the content of a TextBox to be added
我正在使用昵称(名字)。
用户注册时,必须输入昵称,同样,不能包含符号(下划线除外),只能包含数字和字母。
我为此使用了我的 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”写成,但是需要防止那个下划线可以用在最后,我的意思是:
Allow: Hell_o
Prevent: Hello_
这可能吗?
编辑:
I also used String.Last()
but, the result is the same:
if(TextBox.Text.Last() == '_')
{
// Handled = true;
}
除非你能读懂用户的想法,否则你不能这样做:) 毕竟,用户可能想像你的例子中那样输入 Hell_o
但要输入他们首先需要输入 "Hell_" 所以你不能在那个时候阻止他们。您可能要做的最好的事情是处理 UserName 控件上的 "Validating" 事件。
private void UserName_Validating(object sender, CancelEventArgs e) {
errorProvider1.SetError(UserName, "");
if (UserName.Text.EndsWith("_")) {
errorProvider1.SetError(UserName, "Stuff is wrong");
}
}
然后在您的 "register" 按钮点击或其他任何地方,检查该控件(或您关心的任何控件)是否有错误。
我正在使用昵称(名字)。
用户注册时,必须输入昵称,同样,不能包含符号(下划线除外),只能包含数字和字母。
我为此使用了我的 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”写成,但是需要防止那个下划线可以用在最后,我的意思是:
Allow: Hell_o
Prevent: Hello_
这可能吗?
编辑:
I also used
String.Last()
but, the result is the same:
if(TextBox.Text.Last() == '_')
{
// Handled = true;
}
除非你能读懂用户的想法,否则你不能这样做:) 毕竟,用户可能想像你的例子中那样输入 Hell_o
但要输入他们首先需要输入 "Hell_" 所以你不能在那个时候阻止他们。您可能要做的最好的事情是处理 UserName 控件上的 "Validating" 事件。
private void UserName_Validating(object sender, CancelEventArgs e) {
errorProvider1.SetError(UserName, "");
if (UserName.Text.EndsWith("_")) {
errorProvider1.SetError(UserName, "Stuff is wrong");
}
}
然后在您的 "register" 按钮点击或其他任何地方,检查该控件(或您关心的任何控件)是否有错误。