What is the best way to clear all controls on a form C#?

前端 未结 8 2211
情书的邮戳
情书的邮戳 2020-11-27 18:00

I do remember seeing someone ask something along these lines a while ago but I did a search and couldn\'t find anything.

I\'m trying to come up with the cleanest wa

8条回答
  •  没有蜡笔的小新
    2020-11-27 18:13

    Here is the same thing that I proposed in my first answer but in VB, until we get VB10 this is the best we can do in VB because it doesn't support non returning functions in lambdas:

    VB Solution:

    Public Module Extension
        Private Sub ClearTextBox(ByVal T As TextBox)
            T.Clear()
        End Sub
    
        Private Sub ClearCheckBox(ByVal T As CheckBox)
            T.Checked = False
        End Sub
    
        Private Sub ClearListBox(ByVal T As ListBox)
            T.Items.Clear()
        End Sub
    
        Private Sub ClearGroupbox(ByVal T As GroupBox)
            T.Controls.ClearControls()
        End Sub
    
         _
        Public Sub ClearControls(ByVal Controls As ControlCollection)
            For Each Control In Controls
                If ControlDefaults.ContainsKey(Control.GetType()) Then
                    ControlDefaults(Control.GetType()).Invoke(Control)
                End If
            Next
        End Sub
    
        Private _ControlDefaults As Dictionary(Of Type, Action(Of Control))
        Private ReadOnly Property ControlDefaults() As Dictionary(Of Type, Action(Of Control))
            Get
                If (_ControlDefaults Is Nothing) Then
                    _ControlDefaults = New Dictionary(Of Type, Action(Of Control))
                    _ControlDefaults.Add(GetType(TextBox), AddressOf ClearTextBox)
                    _ControlDefaults.Add(GetType(CheckBox), AddressOf ClearCheckBox)
                    _ControlDefaults.Add(GetType(ListBox), AddressOf ClearListBox)
                    _ControlDefaults.Add(GetType(GroupBox), AddressOf ClearGroupbox)
                End If
                Return _ControlDefaults
            End Get
        End Property
    
    End Module
    

    Calling:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Me.Controls.ClearControls()
        End Sub
    

    I'm just posting this here so that people can see how to do the same thing in VB.

提交回复
热议问题