views:

4206

answers:

6

I have implemented validation rules on a textBox in my WinForm and it works well. However it checks the validation only when I tab out of the field. I would like it to check as soon as anything is entered in the box and everytime the content changes. Also I'd like it to check validation as soon as the WinForm opens.

I remember doing this fairly recently by setting some events and whatnot, but I can't seem to remember how.

+2  A: 

You should be checking on KeyPress or KeyDown events and not just your TextChanged event.

Here is a C# Example direct from the MSDN documentation:

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}
TheTXI
+2  A: 

TextChanged event

in the future you can find all of the events on the MSDN library, here's the TextBox class reference:

http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(VS.80).aspx

Jason
TextChanged event will only fire once focus has been lost from the control (such as from a tab out). This will only prevent invalid data from being entered once you leave. The OP appears to want to prevent it from ever being allowed period.
TheTXI
That's not accurate, TextChanged fires regardless of focus.
Hans Passant
I stand corrected
TheTXI
A: 

How will your data be valid if it isn't finished? i.e. a user types a number and you try and validate it as a date?

ck
my guess is its a numeric field that can't contain letters, or vice versa
Jason
This is quite common if you want to prevent people from inputting invalid characters. If you check on KeyPress or KeyDown, you can trap the input and keep it from ever showing up.
TheTXI
Thats the whole point. The data is not valid when it's not finnished so we would like to have the error appear whenever the field contains invalid data. This includes at startup and when typing as long as the data is invalid still.
Sakkle
Ook, fair enough if you don't mind telling the user that their input is invalid, but I would personally not be impressed if a system told me my data was invalid when I started typing.
ck
ck: It doesn't need to tell you. You can just as easily write your code to prevent those illegal characters from showing up so that if you start banging away "123abc4565" your "abc" won't show up because the code took care of it behind the scenes.
TheTXI
@ck, I agree with you in that this is not how I would personally do it, but this is how the old system we are migrating works so there is a user demand that it continue to be like that. Users will allways resist change... :P
Sakkle
@TheTXI: I see your point, in that situation intercepting each key press would indeed be a benefit.
ck
A: 

As an option if you need to validate a date, certain type of number e.g. ISBN I would recommend looking into using Regular Expressions to help validate the data in your textbox.

That way, when you need to check for a certain string pattern you can pass it to a Regular Expression you defined to see if it evaluates as true.

Example for checking with date formate.

Imports System.Text.RegularExpressions
Public Class Form1

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged

    Dim regExp As String = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d"
    Dim matobj As Match = Regex.Match(TextBox1.Text, regExp)

    If matobj.Success = True Then
        MsgBox("Correctly Formatted")
    Else
        MsgBox("Not Correctly Formatted")
    End If

End Sub    
End Class

NOTE: I know for checking something like the date its much easier to use the format function of the string, but i just wanted to show an easy example how you apply it.

Sorry for the overkill.

kevchadders
This doesn't answer the question
Gavin Miller
Think the downvote was a little harsh... :)
Sakkle
+1  A: 

If you're using databinding, go to the Properties of the textbox. Open (DataBindings) at the top, click on the (Advanced) property, three dots will appear (...) Click on those. The advanced data binding screen appears. For each property of the TextBox that is bound, in your case Text, you can set when the databinding, and thus the validation, should "kick in" using the combobox Data Source Update mode. If you set it to OnPropertyChanged, it will re-evaluate as you type (the default is OnValidation which only updates as you tab).

Kurt Schelfthout
+1  A: 

When binding your textbox to a bindingSource go to Advanced and select validation type
"On Property Changed". This will propagate your data to your entity on each key press. Here is the screen shot

Valentin Vasiliev