如何使用foreach循环清除所有文本框?

时间:2013-10-03 08:51:17

标签: asp.net c#-4.0

 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";

}

如何使用foreach循环方法替换为clear()..请告诉我..任何一个... 是不是可以编写foreach循环...请告诉我

4 个答案:

答案 0 :(得分:6)

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);  
        }
    }
}

然后像这样调用这个方法:

ClearAllControlsRecursive(yourContainer);

您也可以打开控件类型并相应地清除值。

答案 1 :(得分:2)

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



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


    }
}

我认为这个方法就像......

ClearAllControlsRecursive(panel1);

答案 2 :(得分:1)

你可以这样尝试

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

答案 3 :(得分:0)

您可以使用此扩展方法:

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;
}

here是一个代码(回答问题),用于清除表单上的所有控件。

另一种方法

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