0

I am writing a program which involves a few Groupboxes and a sub-routine to manipulate the controls in each of the groupboxes (e.g. add buttons, remove controls) according the variables given e.g. GroupBA, GroupBD....etc.

However, I received "NullReferenceException" unless I write the hardcode to specify the exact name of Groupbox like Me.GroupBA.Controls.clear() to action.

Is there any way to handle those groupbox in an array to avoid any repeated code?

e.g. 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
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 2
    Consider `WorkGP.Controls.Clear()`, the argument should be `WorkGP As GroupBox`. Do note that this is a normally a very nasty memory leak, controls that you remove like that also need to be disposed. Best way is While WorkGP.Controls.Count > 0: WorkGP(0).Dispose(): End While. – Hans Passant Jun 23 '18 at 16:20
  • You could approach this a couple different ways. You could maintain a `List(Of Control` (or `List(Of GroupBox)`) and loop over that... Or you could write a recursive function that finds all GroupBoxes on the form and clears them of controls. When choosing a strategy you should always keep maintainability and performance in mind. – Sam Axe Jun 23 '18 at 17:41

1 Answers1

-2

I have made a sub for my own.. but I think that it can help you after doing some modifications..

       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