Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

How to Display a Control's Hierarchy as a String

0.00/5 (No votes)
26 Feb 2013CPOL 9.4K  
Here's how to display a control's hierarchy as a string

I created an extension method that allows my program to find all of a control's parents' names. It returns a string separated overrideable delimiter (::).  This code is targeted for .NET 4 Client, but should also work in .NET 3.5.

VB.NET
Module WinformControlExtensions
  ''' <summary>
  ''' Find all of the control's parents' names and return a string of the complete hierarchy
  ''' </summary>
  ''' <param name="Control"><c><seealso cref="System.Windows.Forms.Control">Control</seealso></c> 
  ''' from which to display the hierarchy.</param>
  ''' <returns><c><seealso cref="String">String</seealso></c> of the parents' names.</returns>
  ''' <remarks></remarks>
  <System.Runtime.CompilerServices.Extension()>
  Public Function ToControlHierarchy(ByRef Control As Control, _
                                     Optional ByVal Separator As String = "::") As String
    Dim oStack As New Stack()

    Dim oParent As Control = Control.Parent
    oStack.Push(Control.Name)
    Do Until IsNothing(oParent)
      oStack.Push(oParent.Name)
      oParent = oParent.Parent
    Loop

    Dim sFullName As String = String.Empty
    Do While oStack.Count > 0
      sFullName &= oStack.Pop() & Separator
    Loop

    Return sFullName.Substring(0, sFullName.Length - Separator.Length)
  End Function
End Module

An example usage:

VB.NET
Dim oList As List(Of Control) = Me.FindAllChildren()

Dim oControl As Control
For Each oControl In oList
  Console.WriteLine(oControl.ToControlHierarchy("!"))
Next

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)