You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBNET嵌套用户控件Child_1如何访问父控件Child的公开只读属性

VB.NET 嵌套用户控件父级属性访问实现方案

层级关系确认:MAIN(FORM) → Child(USERCONTROL) → Child_1(USERCONTROL),其中Child暴露只读属性IdBase、IdUser,取值绑定内部DGV的CurrentRow。
以下是两种稳定的实现方式:

方法1:父容器递归查找法(无需修改控件初始化逻辑)

适合Child_1和Child之间可能嵌套其他容器(如Panel、GroupBox)的场景,通过递归向上查找类型匹配的父控件:
在Child_1的代码文件中添加如下逻辑:

' 通用递归查找指定类型的父控件
Private Function FindParentControl(Of T As Control)(ByVal ctrl As Control) As T
    If ctrl.Parent Is Nothing Then Return Nothing
    If TypeOf ctrl.Parent Is T Then
        Return CType(ctrl.Parent, T)
    End If
    Return FindParentControl(Of T)(ctrl.Parent)
End Function

' 需要获取属性时调用示例
Private Sub GetParentPropertyDemo()
    Dim parentChild As Child = FindParentControl(Of Child)(Me)
    If parentChild IsNot Nothing Then
        ' 访问两个属性
        Dim currentIdBase = parentChild.IdBase
        Dim currentIdUser = parentChild.IdUser
        ' 后续业务逻辑
    End If
End Sub

注意:调用前需判断返回的parentChild是否为空,避免控件未加载完成时触发空引用异常。


方法2:依赖注入法(性能最优、稳定性最高)

提前将父控件实例注入到Child_1中,无需运行时查找,适合所有场景:

  1. 首先在Child_1的代码中公开父控件引用属性:
' 定义公开的父控件引用属性
Public Property ParentChildInstance As Child
  1. 在Child控件的Load事件,或者Child中初始化Child_1的位置,将自身实例赋值给该属性:
' Child控件的代码中,假设Child_1的实例名为Child_11
Private Sub Child_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.Child_11.ParentChildInstance = Me
End Sub
  1. 之后在Child_1的任意位置都可以直接访问属性:
If ParentChildInstance IsNot Nothing Then
    Dim currentIdBase = ParentChildInstance.IdBase
    Dim currentIdUser = ParentChildInstance.IdUser
End If

额外注意事项

由于IdBase、IdUser取值依赖DGV的CurrentRow,建议在Child的属性定义中增加空判断,避免DGV无选中行时抛出异常:

' Child控件中属性定义示例
Public ReadOnly Property IdBase As Integer?
    Get
        If DataGridView1.CurrentRow Is Nothing Then Return Nothing
        Return CInt(DataGridView1.CurrentRow.Cells("IdBaseColumn").Value)
    End Get
End Property

内容的提问来源于stack exchange,提问作者Adelina Andreea trandafir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:45:00