Foreach Control in form, how can I do something to all the TextBoxes in my Form?

后端 未结 14 1552
野的像风
野的像风 2020-11-28 08:13

How can I use a Foreach Statement to do something to my TextBoxes?

foreach (Control X in this.Controls)
{
    Check if the controls is a TextBox, if it is de         


        
14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 08:44

    If you are using C# 3.0 or higher you can do the following

    foreach ( TextBox tb in this.Controls.OfType()) {
      ..
    }
    

    Without C# 3.0 you can do the following

    foreach ( Control c in this.Controls ) {
      TextBox tb = c as TextBox;
      if ( null != tb ) {
        ...
      }
    }
    

    Or even better, write OfType in C# 2.0.

    public static IEnumerable OfType(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(this.Controls)) {
      ..
    }
    

提交回复
热议问题