I don't understand why it would go to the End Function line and then jump back into the code?
This is to be expected. When a function returns, the execution goes back to the previous stack frame and resumes from where it left. This is exactly what your code does.
The confusing part comes from the fact that your function is recursive. You are under the impression that the code simply moves from the Return
statement line back into a given position within code, similar to a GOTO
operation. But truth is that the stack does in fact go down one frame, back to completing the previous call to the same function.
If you want to check this out, simply run your code in debug mode and watch the value of the returnValue
variable. Right after the code "jumps back", you'll see that it will be pointing to a different value. This is because the execution is now back to completing the parent call, for which the value has been kept in memory.
In fact, that last part is actually one reason why you'd want to be very careful when making recursive calls. The deeper they go, the more memory they require. You can read about it here:
Recursive Procedures (Visual Basic) - MSDN
As of why your actual code doesn't work the way you want, it looks like you never use the returned value of the nested call to getcontrolType
function. Change that part to this instead:
If ctrl.HasChildren Then
Return getcontrolType(controlString, ctrl)
End If
If I may, I would also suggest that you change your function's name to GetControlName
and use System.String
as the return type.
Or better yet: name it GetControl
and have it return the instance of the found control (with return type being System.Windows.Forms.Control
).
EDIT:
Are you aware of the ControlCollection.Find method? It might give you what you want much more efficiently:
Dim controlToFind = parentControl.Controls.Find("myControlName", True).SingleOrDefault();