How to use foreach loop to clear all text fields?

 public void clear()
  {
    lblage.Text = "";
    lblclosingbirds.Text = "";
    lbltypeoffeed.Text = "";
    lbltypeoffeedf.Text = "";
    lblstdfeed.Text = "";
    lblstdfeedf.Text = "";
    lblstdhd.Text = "";
    lblstdhe.Text = "";
    lblExpeggs.Text = "";
    lblbirdsf.Text = "";
    txtacteggs.Text = "";
    txtactfeed.Text = "";
    txtactfeedf.Text = "";      
    txtfemaleclosingstock50.Text = "";
    txtfemaleclosingstock70.Text = "";
    txtmale50kgcstock.Text = "";
    txtmale70kgscstock.Text = "";
    txtmort.Text = "";
    txtmortf.Text = "";
    txtuseeggs.Text = "";
    ddlFemaleFeedtype.SelectedValue = "0";
    ddlMaleFeedtype.SelectedValue = "0";

}

How to use the foreach loop method to replace with clear () .. please tell me .. anyone ... is it possible to write a foreach loop ... please tell me

+4
source share
4 answers
void ClearAllControlsRecursive(Control container)
{
    foreach(var control As Control in container.Controls)
    {
        if(typeof control is TextBox)
        {
            ((TextBox)control).Text = String.Empty;
        }
        if(control.HasControls())
        {
            ClearAllControlsRecursive(control);  
        }
    }
}

then call this method as follows:

ClearAllControlsRecursive(yourContainer);

You can also enable the control type and clear the values ​​accordingly.

+6
source
void ClearAllControlsRecursive(Control container)
{
    foreach (var control in container.Controls)
    {



        if (control is TextBox)
        {
            ((TextBox)control).Text = String.Empty;
        }


    }
}

and this method is like ...

ClearAllControlsRecursive(panel1);
+2
source

foreach (object control in form1.Controls) {
    if (control is TextBox) {
        control.Text = "";
    }
}
+1

:

public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control
    {
        var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
        return children.SelectMany(c => GetChildControls(c)).Concat(children);
    }

:

foreach (TextBox tb in this.GetChildControls<TextBox>())
{
    tb.Text = String.Empty;
}

- ( ), .

:

yourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
0

All Articles