【问题标题】:VB.net Working with GroupBox in ArrayVB.net 使用数组中的 GroupBox
【发布时间】:2018-12-02 19:11:32
【问题描述】:

我正在编写一个程序,该程序涉及几个 Groupbox 和一个子例程,用于根据给定的变量(例如添加按钮、删除控件)操作每个 groupbox 中的控件(例如添加按钮、删除控件)。 GroupBA、GroupBD....等

但是,我收到“NullReferenceException”,除非我编写硬代码来指定 Groupbox 的确切名称,例如 Me.GroupBA.Controls.clear() 以执行操作。

有什么方法可以处理数组中的那些分组框以避免重复代码?

例如ClearAllControls(GroupBA)

Sub ClearAllControls (WorkGP) 

    Me.GroupBA.Controls.Clear() 'The code only works if targeted the "GroupBA"
    Me.Controls(WorkGP).Controls.Clear() 'Resulted Error NullReferenceException
    Me.Controls("GroupBA").Controls.Clear() 'Resulted Error NullReferenceException
End

【问题讨论】:

  • 考虑WorkGP.Controls.Clear(),参数应该是WorkGP As GroupBox。请注意,这通常是一个非常严重的内存泄漏,您删除的控件也需要处理。最好的方法是 While WorkGP.Controls.Count > 0: WorkGP(0).Di​​spose(): End While.
  • 你可以通过几种不同的方式来解决这个问题。您可以维护一个List(Of Control(或List(Of GroupBox))并对其进行循环......或者您可以编写一个递归函数来查找表单上的所有GroupBoxes并清除它们的控件。在选择策略时,您应该始终牢记可维护性和性能。

标签: arrays vb.net nullreferenceexception groupbox


【解决方案1】:

我自己做了一个子..但我认为在做一些修改后它可以帮助你..

       Public Sub SetTxtEnterLeave(Parent As Object)


            If Parent.GetType.GetProperty("Controls") Is Nothing Then Exit Sub


            For Each c As Control In Parent.Controls
                If c.GetType.Name = "GroupBox" Then         
                   'add the action here whatever you want to do.....
                End If
            Next

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2013-11-20
    • 1970-01-01
    • 2013-01-14
    相关资源
    最近更新 更多