I'm trying to create a function that searches up a WebControl's parent-child relationship (basically the opposite of WebControl.FindControl(id as String), but looking for a specific WebControl type).
Example: I have a user control in an ItemTemplate for a GridViewRow. I'm trying to reference the GridViewRow from the user control. The user control may or may not be inside a div or other types of controls, so I don't know exactly how many parent's up to look (i.e. I can't just use userControl.Parent.Parent). I need a function that will find the first GridViewRow that it finds on the way up the parent-child hierarchy.
Thus the need for this function. Unless there's a better way to do this? Anyway, I want to the function I'm creating to be fairly generic, so that different WebControl types (i.e. GridViewRow, Panel, etc.) can be specified depending on what I'm looking for. Here's the code I've written:
Public Function FindParentControlByType(ByRef childControl As WebControl, ByVal parentControlType As WebControl.Type, Optional ByRef levelsUp As Integer = Nothing) As WebControl
Dim parentControl As WebControl = childControl
Dim levelCount = 1
Do While Not parentControl.GetType = parentControlType
If Not levelsUp = Nothing AndAlso levelCount = levelsUp Then
parentControl = Nothing
Exit Do
End If
levelCount += 1
parentControl = parentControl.Parent
Loop
parentControl.FindControl(
Return parentControl
End Function
I know the "ByVal parentControlType as WebControl.Type" in the function definition won't work -- that's what I'm looking for.
I'm sure there's a better way to do this, so please feel free to make me look simple by point it out!
Thanks Guys!