How to get the highest parent(The form in which the user control is located) of an object(user control)

Mansour_Dalir 1,676 Reputation points
2024-04-23T06:29:36.65+00:00

When I want to reach the highest parent(meaning the same form) in my fake user control , these are returned due to the placement of the user control in (TableLayoutPanel, Panel, TabControl,...).

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,608 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 27,241 Reputation points Microsoft Vendor
    2024-04-23T07:07:09.82+00:00

    Hi @Mansour_Dalir ,

    You can recursively traverse the parent hierarchy until you find a form.

    Public Module UserControlExtensions
        <Runtime.CompilerServices.Extension()>
        Public Function GetTopLevelForm(control As Control) As Form
            Dim parentForm As Form = TryCast(control, Form)
    
            While parentForm Is Nothing AndAlso control IsNot Nothing
                control = control.Parent
                parentForm = TryCast(control, Form)
            End While
    
            Return parentForm
        End Function
    End Module
    
    

    Then use this extension method on your UserControl instances like this:

    Dim topLevelForm As Form = UserControlExtensions.GetTopLevelForm(Me)
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful