我是Visual Basic.NET的新手,我需要写一段代码来找到Windows窗体中(用户控件/控件)的最顶级父级。
我在Windows窗体上有数百个控件,有些是用户控件和一些内置的Windows控件
我测试的代码是添加多个IF条件,但是当控件嵌套多于2个级别时,很难添加IF条件。
像: 的表 - 面板 - - 面板 ------分组框中 --------文本框
'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
如果有人在这方面指导我,我将非常感激。
答案 0 :(得分:3)
这是通过递归完成的:
#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
它非常适合我。
答案 1 :(得分:2)
这里不需要递归。
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
答案 2 :(得分:2)
* *您可以使用
Dim Form As System.Windows.Forms.Form
Form = Combobox.FindForm()
'直接找到任何控制的父母形式,直到* *
答案 3 :(得分:1)
最终将是形式,但你真的在寻找一种方法来追踪,你可以使用递归或循环:
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
答案 4 :(得分:0)
最简单
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