简体   繁体   中英

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

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.

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM