Search code examples
c#stringwinformstextbox

Prevent an underscore "_" at the end of the content of a TextBox to be added


I am working with nicks (given names).

When a user registers, you must enter your nick, the same, it cannot contain symbols (except the underscore), only numbers and letters.

I use the KeyPress event of my TextBox Username for this:

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;
}

This piece of code prevents that symbols (different from " _ "), the content starts with " _ " and used more than one underscore "H_E_L_L_O" written, but they need to prevent that the underscore can be used at the end, I mean:

Allow: Hell_o

Prevent: Hello_

Is this possible?

Edit:

I also used String.Last() but, the result is the same:

if(TextBox.Text.Last() == '_')
{
   // Handled = true;
}

Solution

  • You can't do this unless you can read the user's mind :) After all, the user might want to put Hell_o like in your example but to type that they first need to type "Hell_" so you can't stop them at that point. The best you're probably going to do is handle the "Validating" event on the UserName control.

    private void UserName_Validating(object sender, CancelEventArgs e) {
        errorProvider1.SetError(UserName, "");
        if (UserName.Text.EndsWith("_")) {
            errorProvider1.SetError(UserName, "Stuff is wrong");
        }            
    }
    

    Then in your "register" button click or whatever, check whether that control is (or any control you care about) is in error.