Lost in a loop

dotnot

Member
Joined
Nov 24, 2004
Messages
6
Programming Experience
Beginner
Apologies if this is not in the correct section.

I'm having a problem validating controls by looping through all controls on my form.
So far I've got :

If ValidateData(Me) Then
'do database update

In my validateData function I have :

Private Function ValidateData(ByVal ctl As Control) As Boolean
'Loop through all the controls and child controls on the form
'if the control is a textbox then check the data entered is valid
'

If TypeOf ctl Is TextBox Then
If ctl.Text.Length > 0 Then
If Not IsNumeric(ctl.Text) Then
messagebox.show("data is bad")
ctl.Focus()
Return False
Exit Function
End If
End If
End If

If ctl.HasChildren Then
For Each c As Control In ctl.Controls
ValidateData(c)
Next
End If

End Function


The problem is that when two textbox control have bad data, I get two message box prompts (one straight after the other). I was trying to get the function to return each time it found bad data, but I appear to be lost in a loop somewhere.
Can anyone advise where I have gone wrong? Sorry - I'm very new to VB so it's most likely something really o**ious.

Thanks
 
How to Validate

Dear fellow , your loop seem to bit ok but u mess into recursion here is correct code,
Private Function ValidateData(ByVal ctl As Control) As Boolean

'Loop through all the controls and child controls on the form

'if the control is a textbox then check the data entered is valid

'

If TypeOf ctl Is TextBox Then

If ctl.Text.Length > 0 Then

If Not IsNumeric(ctl.Text) Then

messagebox.show("data is bad")

ctl.Focus()

Return False

Exit Function

End If

End If

End If

If ctl.HasChildren Then

For Each c As Control In ctl.Controls

If ValidateData(c) = False Then

Exit For

End If

Next

End If

Return True

End Function

 
Thanks for that. Still doesn't seem to do the trick. Although it does pop the error message, it keeps looping and then always returns true at the end of the function. I will keep messing around and hopefully I can work it out. Thanks for the assistance.
 
oh yeah sorry ! to return the False from the function , u need to replace "Exit For" to "Return False" in the second loop that iterates the children controls.
 
Back
Top