Trouver des parents ultimes d'un contrôle dans vb.net
-
21-12-2019 - |
Question
Je suis nouveau à Visual Basic.net, je dois écrire un morceau de code pour trouver le plus haut des parents d'un (contrôle / contrôle de l'utilisateur) sous forme Windows.
J'ai des centaines de commandes sur le formulaire Windows, certaines sont des contrôles utilisateur et des contrôles Windows intégrés
Le code que j'ai testé ajoute de plusieurs conditions, mais lorsque des contrôles sont nichés plus de 2 niveaux, il est difficile d'ajouter si des conditions.
J'aime:
'Here is simple code
'A TextBox inside Panel control
Dim parent_control As Control = TryCast(txtbox, Control) 'casting that Control in generic Control
if parent_control.Parent Is Nothing Then
Return
Else
Return parent_control.Parent.Parent
End If
Je serais très reconnaissant si quelqu'un me guide à cet égard.
La solution
ici est fait par récursivité:
#Region "Get Ultimate Parent"
Private Function GetParentForm(ByVal parent As Control) As Control
Dim parent_control As Control = TryCast(parent, Control)
'------------------------------------------------------------------------
'Specific to a control means if you want to find only for certain control
If TypeOf parent_control Is myControl Then 'myControl is of UserControl
Return parent_control
End If
'------------------------------------------------------------------------
If parent_control.Parent Is Nothing Then
Return parent_control
End If
If parent IsNot Nothing Then
Return GetParentForm(parent.Parent)
End If
Return Nothing
End Function
#End Region
Cela a fonctionné parfaitement pour moi.
Autres conseils
Pas besoin de récursion ici.
Private Function UltimateParent(ByVal control as Control) As Control
Do
If Nothing Is control.Parent
Return control
Else
control = control.Parent
End If
Loop
End Function
**You can use just do
Dim Form As System.Windows.Forms.Form
Form = Combobox.FindForm()
'to find directy the parent form of any controle without any For until**
the ultimate would be the form, but you are really looking for a method to trace through, you could use either recursion or while loop:
Public Function FindTopMostParent(ctrl As Control) As Control
If ctrl.Parent Is Nothing Then
Return ctrl '// or nothing?
End If
Return FindTopMostParent(ctrl.Parent)
End Function
Public Function FindTopMostParent_v2(ctrl As Control) As Control
Dim output As Control = ctrl
While output.Parent IsNot Nothing
output = output.Parent
End While
Return output
End Function
Simplest
Public Function GetUltimateParent(ByVal ofThisControl As Control) As Control
If ofThisControl Is Nothing return Nothing 'Error Check
Dim ultimateParent As Control = ofThisControl
While Not ultimateParent.Parent Is Nothing
ultimateParent = ultimateParent.Parent
End While
Return ultimateParent
End Function