0

I have a small piece of code that I have been trying to get to work, but nope. So I've come to the experts. I'm trying to test a zip code entry and limit it to 5 digits only. My first issue is with the attached code. It doesn't seem to be counting the length properly. Also, how can I limit the user so if they try to type a 6th character, it won't show or be accepted?

private void textBoxZip_TextChanged(object sender, EventArgs e)
    {
        String userInputString;
        int length,
            max = 5;

        userInputString = textBoxZip.Text;
        numberTest(userInputString);

        length = userInputString.Length;
        if (length > max)
        {
            labelErrorMessage.Text = "Maximum length 5 numbers";
        }
    }
user2297683
  • 406
  • 1
  • 5
  • 15

3 Answers3

0

You should look at events KeyDown and KeyPress. See example in MSDN Control.KeyPress Event

Lex
  • 319
  • 1
  • 4
0

If you are in a WinForms application, you can limit a textbox's length by setting the MaxLength property.

Narsters
  • 596
  • 5
  • 4
0

I think using a MaskedTextBox would be an easy solution. This will allow you to easily accept only a certain # of characters in a specified format.

The MaskedTextBox is a standard .NET control in the control toolbar in Visual Studio.

Inisheer
  • 20,376
  • 9
  • 50
  • 82
  • This was a great suggestion as it corrected a couple of issues I had elsewhere. Question though. Is there a way to make the ________ go away? I just want a blank space. – user2297683 Apr 19 '13 at 17:33
  • Unfortunately, I don't know of a way to get rid of that line. – Inisheer Apr 19 '13 at 18:02
  • Found the answer here: http://stackoverflow.com/questions/1459797/hiding-the-promptchar-for-nets-maskedtextbox – user2297683 Apr 19 '13 at 18:23