Domanda

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";
        }
    }
È stato utile?

Soluzione

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.

Altri suggerimenti

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top