Right way to perform validation on a text box

  • Thread starter Thread starter Marina
  • Start date Start date
M

Marina

Hi,

Here is the desire behavior, when the user tries to leave a field, that
field is validated. If the value in the field is invalid, the previous
value is restored - however, the user is allowed to go on to the next field
anyway.

It seems that the Validating event has the behavior of keeping the user in
the field if e.Cancel is set to True - and doesn't replace the bad value
with the last good one. Which is all very undesirable! It means the user
can't even close the program until a valid value is entered into the field!
Why would anyone want this behavior?

Is there any built in way to get the functionality I am looking for, or does
it all have to be done manually?

Thanks
 
I do not know of a built-in way to do what you want... but you can easily
define a class that inherits from System.Windows.Forms.TextBox, and adds
that functionality. Simply define all the textboxes on your form to derive
from your class instead of directly from System.Windows.Forms.TextBox

That's not so hard.
 
It seems that the Validating event has the behavior of keeping the user in
the field if e.Cancel is set to True - and doesn't replace the bad value
with the last good one. Which is all very undesirable! It means the user

Keep the value of the field in a class member or in a variable. Then in
the validating event, if the value in the textbox is not valid restore the
textbox from the variable. If the value is ok, then in the validated
event, set the variable with the value in the text box.

Something like this (pseudocode):

Private txtBoxValue As String

Private Sub TextBox1_Validating(...)
If Not TextBoxContentsValid Then
TextBox1.Text = txtBoxValue 'Restore previous value
e.Cancel = True
End If
End Sub

Private Sub TextBox1_Validated(...)
txtBoxValue = TextBox1.Text 'Save the good value
End Sub

Never use interface elements (textboxes, etc.) to be the storage for your
data. Always use a class or variable and only use interface elements to
reflect what is contained in the variable.
can't even close the program until a valid value is entered into the field!
Why would anyone want this behavior?

As far as not being able to close the app if the field is not valid, I
tend to use a close button that has it's CausesValidation property set to
False so that validation does not occur when I click that button.

HTH

--
Chris

dunawayc[AT]sbcglobal_lunchmeat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
 
Back
Top