LARC
LARC

Reputation: 109

Get the name of the Parent of a child Panel

I have a Panel object, which was dynamically created within another Panel object that was also dynamically created.
How can I get the name of the parent Panel from the child Panel?.

I only found information related to the Form object.

Upvotes: 0

Views: 973

Answers (1)

Jimi
Jimi

Reputation: 32223

A couple of methods that may help in finding the child's Parents.

The direct parent of a Control is returned by the Control.Parent property:

Dim parentName = [SomeControl].Parent.Name

The Form container is returned by the FindForm() method or the Control.TopLevelControl property:

Dim myForm1 = [SomeControl].FindForm()
Dim myForm2 = [SomeControl].TopLevelControl
Dim myFormName1 = myForm1.Name
Dim myFormName2 = myForm2.Name

You may also use GetContainerControl(), this returns the outermost IContainerControl.

A UserControl can use the ParentForm property (but it's the same as FindForm())

To find the outer container that is not a Form:

Private Function FindOuterContainer(ctrl As Control) As Control
    If ctrl Is Nothing Then Return Nothing
    While Not (TypeOf ctrl.Parent Is Form)
        ctrl = FindOuterContainer(ctrl.Parent)
    End While
    Return ctrl
End Function

Dim outerContainer = FindOuterContainer([SomeControl])
Dim outerContainerName = outerContainer.Name

To find the outer ancestor of a specific type (e.g., you have a Panel inside a Panel inside a TabPage of a TabControl and you want to know what TabPage that is):

Private Function FindOuterContainerOfType(Of T)(ctrl As Control) As Control
    If ctrl Is Nothing Then Return Nothing
    While Not ((TypeOf ctrl.Parent Is Form) OrElse (TypeOf ctrl Is T))
        ctrl = FindOuterContainerOfType(Of T)(ctrl.Parent)
    End While
    Return ctrl
End Function

Dim parentTabPage = FindOuterContainerOfType(Of TabPage)([SomeControl])
Console.WriteLine(parentTabPage.Name)

To find the outermost Parent of a specific type:
(e.g., you have a Panel inside a Panel inside a TabPage of a TabControl which is inside a Panel and you want to get this last Panel)

Private Function FindOuterMostContainerOfType(Of T)(ctrl As Control) As Control
    If ctrl Is Nothing Then Return Nothing
    Dim outerParent As Control = Nothing
    While Not (TypeOf ctrl.Parent Is Form)
        If TypeOf ctrl.Parent Is T Then outerParent = ctrl.Parent
        ctrl = ctrl.Parent
    End While
    Return If(TypeOf outerParent Is T, outerParent, Nothing)
End Function


Dim outermostParentPanel = 
    TryCast(FindOuterMostContainerOfType(Of Panel)([SomeControl]), Panel)
Dim outermostParentPanelName = outermostParentPanel?.Name

[SomeControl] is of course the instance of the child Control that wants to find its Parents.

Upvotes: 1

Related Questions