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

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

提交回复
热议问题