VB.NET - Iterating through controls in a container object

后端 未结 10 1345
别那么骄傲
别那么骄傲 2020-12-03 05:18

I have a form with a \"Clear\" button.

When the user clicks \"Clear\", I want to clear the value of all the visible elements on the form. In the case of date contro

10条回答
  •  生来不讨喜
    2020-12-03 05:34

    Public Sub raz(lst As Control.ControlCollection, Optional recursive As Boolean = True)
        For Each ctrl As Control In lst
            If TypeOf ctrl Is TextBox Then
                CType(ctrl, TextBox).Clear()
            End If
    
            If TypeOf ctrl Is MaskedTextBox Then
                CType(ctrl, MaskedTextBox).Clear()
            End If
    
            If TypeOf ctrl Is ComboBox Then
                CType(ctrl, ComboBox).SelectedIndex = -1
            End If
    
            If TypeOf ctrl Is DateTimePicker Then
                Dim dtp As DateTimePicker = CType(ctrl, DateTimePicker)
                dtp.CustomFormat = " "
            End If
    
            If TypeOf ctrl Is CheckedListBox Then
                Dim clbox As CheckedListBox = CType(ctrl, CheckedListBox)
                For i As Integer = 0 To clbox.Items.Count - 1
                    clbox.SetItemChecked(i, False)
                Next
            End If
    
            If TypeOf ctrl Is RadioButton Then
                CType(ctrl, RadioButton).Checked = False
    
            End If
    
            If recursive Then
                If TypeOf ctrl Is GroupBox Then
                    raz(CType(ctrl, GroupBox).Controls)
                End If
            End If
        Next
    End Sub
    

提交回复
热议问题