如何在VB.NET中引用发送者控件所在的用户窗体?
问题描述
我通过代码创建了按钮控件及其所在的用户窗体,点击该按钮时,需要引用此用户窗体以获取其中ComboBox(combobox_ProjectType)的选中项作为变量。我可以向下获取发送者的子控件,但不清楚如何向上获取其所在的父窗体?
代码示例:
Sub DynamicForm_NewForm_SmartHUB_ProjectsActivated(ByVal sender As Object, ByVal e As EventArgs) strProjectTypeFolderName = '(form in which the sender is located).combobox_ProjectType.selecteditem End Sub
解决方案
在VB.NET里,有两种简单可靠的方式获取按钮所在的父窗体:
方法1:使用FindForm()直接获取
控件自带的FindForm()方法可以直接返回它所在的顶层窗体,不用逐级找父容器,是最简便的方式:
Sub DynamicForm_NewForm_SmartHUB_ProjectsActivated(ByVal sender As Object, ByVal e As EventArgs) ' 把sender转成Button类型 Dim btn As Button = DirectCast(sender, Button) ' 获取按钮所在的窗体 Dim parentForm As Form = btn.FindForm() If parentForm IsNot Nothing Then ' 从窗体中找到目标ComboBox Dim projectTypeCbo As ComboBox = DirectCast(parentForm.Controls("combobox_ProjectType"), ComboBox) If projectTypeCbo IsNot Nothing AndAlso projectTypeCbo.SelectedItem IsNot Nothing Then strProjectTypeFolderName = projectTypeCbo.SelectedItem.ToString() End If End If End Sub
方法2:创建按钮时绑定窗体引用
如果按钮是动态创建的,可以在创建阶段把窗体对象存到按钮的Tag属性里,后续直接读取:
' 动态创建按钮的代码示例 Dim newBtn As New Button() ' 把当前窗体对象赋值给按钮的Tag newBtn.Tag = Me ' 绑定点击事件 AddHandler newBtn.Click, AddressOf DynamicForm_NewForm_SmartHUB_ProjectsActivated
然后在事件处理方法里直接读取Tag:
Sub DynamicForm_NewForm_SmartHUB_ProjectsActivated(ByVal sender As Object, ByVal e As EventArgs) Dim btn As Button = DirectCast(sender, Button) ' 从Tag里取出窗体对象 Dim parentForm As Form = DirectCast(btn.Tag, Form) If parentForm IsNot Nothing Then Dim projectTypeCbo As ComboBox = DirectCast(parentForm.Controls("combobox_ProjectType"), ComboBox) If projectTypeCbo IsNot Nothing AndAlso projectTypeCbo.SelectedItem IsNot Nothing Then strProjectTypeFolderName = projectTypeCbo.SelectedItem.ToString() End If End If End Sub
注意点
- 如果
combobox_ProjectType放在Panel、GroupBox这类容器控件里,直接用parentForm.Controls("combobox_ProjectType")会找不到,这时候需要递归遍历控件树,或者提前把ComboBox的引用也存到按钮的Tag里。 - 一定要加空值判断,避免出现空引用异常。
内容的提问来源于stack exchange,提问作者Eduards
相关产品推荐
相关产品推荐

