【问题标题】:Prevent an underscore "_" at the end of the content of a TextBox to be added防止在要添加的 TextBox 内容的末尾添加下划线“_”
【发布时间】: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 子句中比较SelectionStartTextLength 不能解决问题吗?
  • this.Handled = false ?那不是e.Handled吗?
  • 这是什么意思:"并且在"H_E_L_L_O"下使用了多个脚本"?
  • @LarsTech Handled 是一个私有布尔值

标签: c# string winforms textbox


【解决方案1】:

除非你能读懂用户的想法,否则你不能这样做:) 毕竟,用户可能希望像在你的示例中那样输入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");
    }            
}

然后在您的“注册”按钮中单击或其他任何内容,检查该控件(或您关心的任何控件)是否有错误。

【讨论】:

  • String.Last()代替String.EndsWith()不是更好吗?
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 2017-06-15
  • 2023-02-18
相关资源
最近更新 更多