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

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

    Below are methods I use to clear text from a type of control that implements ITextBox.

    I noticed in the example default boolean values are set. I'm sure you can modify it to set default values of boolean components.

    Pass the Clear method a control type (TextBox, Label... etc) and a control collection, and it will clear all text from controls that implement ITextBox.

    Something like this:

    //Clears the textboxes
    WebControlUtilities.ClearControls(myPanel.Controls);
    

    The Clear method is meant for a Page or Masterpage. The control collection type may vary. ie. Form, ContentPlaceHolder.. etc

            /// 
        /// Clears Text from Controls...ie TextBox, Label, anything that implements ITextBox
        /// 
        /// Collection Type, ie. ContentPlaceHolder..
        /// ie TextBox, Label, anything that implements ITextBox
        /// 
        public static void Clear(ControlCollection controls)
            where C : ITextControl
            where T : Control
        {
            IEnumerable placeHolders = controls.OfType();
            List holders = placeHolders.ToList();
    
            foreach (T holder in holders)
            {
                IEnumerable enumBoxes = holder.Controls.OfType();
                List boxes = enumBoxes.ToList();
    
                foreach (C box in boxes)
                {
                    box.Text = string.Empty;
                }
            }
        }
    
        /// 
        /// Clears the text from control.
        /// 
        /// 
        /// The controls.
        public static void ClearControls(ControlCollection controls) where C : ITextControl
        {
            IEnumerable enumBoxes = controls.OfType();
            List boxes = enumBoxes.ToList();
    
            foreach (C box in boxes)
            {
                box.Text = string.Empty;
            }
        }
    

提交回复
热议问题