Dark Knight
Dark Knight

Reputation: 3577

dynamic textbox validation in C#

my text box takes only numeric values,from 0 to 255 (1 byte),how can i prevent the user entering the number>255...the moment the 3rd digit is entered it should validate.right now my code validating when you come out of textbox and showing message.Any help greatly appreciated.

  private void cor_o_gain_Validating(object sender, CancelEventArgs e)
    {
        try
        {
            int entered = int.Parse(cor_o_gain.Text);
            if (entered > 255)
            {
                e.Cancel = true;
                MessageBox.Show("Enter the number between 0 and 255");
            }
        }
        catch (FormatException)
        {
          //  e.Cancel = true;
        }
    } 

Upvotes: 0

Views: 2353

Answers (4)

Gerald Davis
Gerald Davis

Reputation: 4549

I would say reconsider your implementation. I have used software designed like that and it is very annoying. It likely going to piss your users off over time and provide no real benefit.

Still if you absolutely MUST stop the user in the middle of typing (once again question if you SHOULD) then you need a "faster acting" event like Keypress.

There are lots of "gentler" implementations though. One option (not the only one) would be to change background color of textbox and make an error message visible to alert but not block the user that the input is invalid. This allows user to change the text without being interrupted (by the message box) while trying to change the text.

Upvotes: 1

Lane
Lane

Reputation: 2719

You should use a numericUpDown control instead, and set the min and max values to be within 0 and 255.

System.Windows.Forms.NumericUpDown n = new System.Windows.Forms.NumericUpDown();
n.Minimum = 0;
n.Maximum = 255;

Upvotes: 2

Eyal
Eyal

Reputation: 5848

You might consider not doing this because it's annoying. If a user types "30" and changes his mind while the cursor is before the 3, he might type "40" and then hit delete twice. Your app would beep at him and show a messagebox.

If you must validate while he's typing, consider putting a label next to his text and updating it to read "Invalid input" or some such. Do it on keypress, keyup or keydown as mentioned elsewhere.

Upvotes: 5

Ahmet Kakıcı
Ahmet Kakıcı

Reputation: 6404

Check out for the key events; keypress, keydown, keyup etc.

Upvotes: 3

Related Questions