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

前端 未结 8 2163
情书的邮戳
情书的邮戳 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:05

    You can loop for control

    foreach (Control ctrl in this)
    {
        if(ctrl is TextBox)
            (ctrl as TextBox).Clear();
    }
    
    0 讨论(0)
  • 2020-11-27 18:05

    I voted for Nathan's solution, but wanted to add a bit more than a comment can handle.

    His is actually very good, but I think the best solution would involve sub-classing each of the control types you might be adding before adding them to the GUI. Have them all implement an interface "Clearable" or something like that (I'm a java programmer, but the concept should be there), then iterate over it as a collection of "Clearable" objects, calling the only method .clear() on each

    This is how GUIs really should be done in an OO system. This will make your code easy to extend in the future--almost too easy, you'll be shocked.

    Edit: (per Nathan's comment about not changing existing controls)

    Perhaps you could create "Container" classes that reference your control (one for each type of control). In a loop like the one you set up in your answer, you could instantiate the correct container, place the real control inside the container and store the container in a collection.

    That way you are back to iterating over a collection.

    This would be a good simple solution that isn't much more complex than the one you suggested, but infinitely more expandable.

    0 讨论(0)
  • 2020-11-27 18:09

    I know its an old question but just my 2 cents in. This is a helper class I use for form clearing.

    using System;
    using System.Windows.Forms;
    
    namespace FormClearing
    {
        class Helper
        {
            public static void ClearFormControls(Form form)
            {
                foreach (Control control in form.Controls)
                {
                    if (control is TextBox)
                    {
                        TextBox txtbox = (TextBox)control;
                        txtbox.Text = string.Empty;
                    }
                    else if(control is CheckBox)
                    {
                        CheckBox chkbox = (CheckBox)control;
                        chkbox.Checked = false;
                    }
                    else if (control is RadioButton)
                    {
                        RadioButton rdbtn = (RadioButton)control;
                        rdbtn.Checked = false;
                    }
                    else if (control is DateTimePicker)
                    {
                        DateTimePicker dtp = (DateTimePicker)control;
                        dtp.Value = DateTime.Now;
                    }
                }
            }
        }
    }
    

    And I call the method from any form like this passing a form object as a parameter.

    Helper.ClearFormControls(this);
    

    You can extend it for other types of controls. You just have to cast it.

    0 讨论(0)
  • 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
    
        <Runtime.CompilerServices.Extension()> _
        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.

    0 讨论(0)
  • 2020-11-27 18:15

    The above solutions seem to ignore nested controls.

    A recursive function may be required such as:

    public void ClearControl(Control control)
    {
      TextBox tb = control as TextBox;
      if (tb != null)
      {
        tb.Text = String.Empty;
      }
      // repeat for combobox, listbox, checkbox and any other controls you want to clear
      if (control.HasChildren)
      {
        foreach(Control child in control.Controls)
        {
          ClearControl(child)
        }
      }
    }
    

    You don't want to just clear the Text property without checking the controls type.

    Implementing an interface, such as IClearable (as suggested by Bill K), on a set of derived controls would cut down the length of this function, but require more work on each control.

    0 讨论(0)
  • 2020-11-27 18:16

    private void FormReset() { ViewState.Clear(); Response.Redirect(Request.Url.AbsoluteUri.ToString()); }

    0 讨论(0)
提交回复
热议问题