将控件类型传递给过程

时间:2013-06-04 20:27:21

标签: .net vb.net visual-studio-2012 casting typeof

我正在尝试通过使用您可以看到的参数调用此过程来创建一个通用过程来将“X”控件对象的visible属性更改为“False / True”:

    ' Desired usage:
    ' Disable_Controls(CheckBox, Me.Panel1.Controls, False)

    Public Sub Disable_Controls(ByVal ControlType As Control, _
                                ByVal Container As ControlCollection, _
                                ByVal Visible As Boolean)

        For Each Control As Control In Container
            ' If TypeOf Control Is CheckBox then...
            If TypeOf Control Is Control Then
                Control.Visible = Visible
            End If
        Next

    End Sub

问题是我无法传递控件名称(“Checkbox”),就像我正在尝试的那样, 我尝试了一些使用“CType(Control,CheckBox)”的东西,但没有用。

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

Public Sub Disable_Controls(Of T As Control)(ByVal Container As Control, _
                            ByVal Visible As Boolean)
    For Each ctrl As T In Container.Controls.OfType(Of T)()
        ctrl.Visible = Visible
    Next
End Sub

这样称呼:

Disable_Controls(Of Checkbox)(MyGroupbox, False)