Нахождение конечного родителя элемента управления в Vb.Net
Я новичок в Visual Basic.NET, мне нужно записать кусок кода, чтобы найти верхний родительский элемент (пользовательский элемент управления / контроль) в форме Windows.
У меня есть сотни элементов управления для формы Windows, некоторые из которых являются пользовательскими и некоторые встроенные элементы управления Windows
Код, который я протестировал, добавляет несколько условий IF, но когда элементы управления вложены более чем в 2 уровня, сложно добавить условия IF.
Как:Форма --Панель ---- Панель ------GroupBox --------TextBox
'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
Я был бы очень благодарен, если бы кто-нибудь направил меня в этом отношении.
5 ответов
Здесь делается через рекурсию:
#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
У меня это сработало отлично.
** Вы можете использовать просто сделать
Dim Form As System.Windows.Forms.Form
Form = Combobox.FindForm()
'найти непосредственно родительскую форму любого контроля без каких-либо до*
Нет необходимости в рекурсии здесь.
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
Конечной будет форма, но вы действительно ищете метод для трассировки, вы можете использовать либо рекурсию, либо цикл while:
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
Самый простой
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