[ACCEPTED]-C# - TextBox Validation-validation

Accepted answer
Score: 15

There are several events that you can use 4 here, Leave, LostFocus and Validating there is more discussion of 3 these various events on MSDN here.

Under certain scenarios 2 the Leave and the LostFocus will not fire so the best 1 to use in your case is the Validating event:

    textBox1.Validating += new CancelEventHandler(textBox1_Validating);


    void textBox1_Validating(object sender, CancelEventArgs e)
    {
        int numberEntered;

        if (int.TryParse(textBox1.Text, out numberEntered))
        {
            if  (numberEntered < 1 || numberEntered > 10) 
            { 
                MessageBox.Show("You have to enter a number between 1 and 10");
                textBox1.Text = 5.ToString();
            }
        }
        else
        {
            MessageBox.Show("You need to enter an integer");
            textBox1.Text = 5.ToString();
        }
    }
Score: 0

Have a look here and I would use the TryParse

0

Score: 0

if you are hand-rolling validation like 7 you do here, all you need to do is to set 6 the default value after you MessageBox.Show()

in 5 standard winforms I don't think you have 4 any framework support for validation, but 3 you could look at this: http://msdn.microsoft.com/en-us/library/ms951078.aspx for inspiration 2 so you don't scatter this logic throughout 1 your app

Score: 0

Use the Leave event on the textbox control to 1 validate and set the default value

More Related questions