Foreach Control在表单中,如何对表单中的所有TextBox进行操作?

Ser*_*pia 25 c# winforms

如何使用Foreach语句对TextBoxes执行某些操作?

foreach (Control X in this.Controls)
{
    Check if the controls is a TextBox, if it is delete it's .Text letters.
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 63

如果您使用的是C#3.0或更高版本,则可以执行以下操作

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
  ..
}
Run Code Online (Sandbox Code Playgroud)

如果没有C#3.0,您可以执行以下操作

foreach ( Control c in this.Controls ) {
  TextBox tb = c as TextBox;
  if ( null != tb ) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,在C#2.0中编写OfType.

public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class { 
  foreach ( object cur in e ) {
    T val = cur as T;
    if ( val != null ) {
      yield return val;
    }
  }
}

foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
  ..
}
Run Code Online (Sandbox Code Playgroud)


Jus*_*ren 59

您正在寻找

foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    ((TextBox)x).Text = String.Empty;
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

这里的诀窍Controls是不是一个List<>IEnumerable一个ControlCollection.

我建议使用Control的扩展名,它将返回更多东西......可以;)

public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

foreach(var textbox in this.Controls.All().OfType<TextBox>)
{
    // Apply logic to the textbox here
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*Ali 5

您也可以使用 LINQ。例如,对于明文Textbox,请执行以下操作:

this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);
Run Code Online (Sandbox Code Playgroud)