JimmyJimm JimmyJimm - 1 year ago 84
Vb.net Question

Close all controls which has specific type

I would like to create function which could take as parameter either usercontrol or windows form and then close all controls on it which are currently opened but only when type of them are either usercontrols or windows forms.

Below find my tries pseudo code:

'take as parameter either usercontrol or winform
Public Shared Sub DisposeUserControlControls(ucOrWinForm As T)

Dim type as Type = GetType(ucOrWinForm)

While type.Controls.Count > 0

'if uc.Control is type of UserControl or WindowsForms then --> close

While type.Controls(0).Controls.Count > 0
End While

End While
End Sub

Answer Source

It is a bit of a code smell. No compelling reason to make it generic, it is just as valid to do this when, say, it is a Panel you want to empty. Do beware that you'll only ever run into a Form object when you set its TopLevel property to False. Since you are going to skip controls of the wrong flavor you cannot use the While-loop anymore. You instead have to iterate backwards. Like this:

Public Shared Sub DisposeUserControlControls(parent As Control)
    For ix As Integer = parent.Controls.Count - 1 To 0 Step -1
        Dim ctl = parent.Controls(ix)
        If (TypeOf ctl Is UserControl) Or (TypeOf ctl Is Form) Then
        End If
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download