c# - Foreach 控件在窗体中,我怎样才能对我的窗体中的所有文本框做些什么?

标签 c# winforms

如何使用 Foreach 语句对我的文本框执行某些操作?

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

最佳答案

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

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

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

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

或者更好的是,在 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)) {
  ..
}

关于c# - Foreach 控件在窗体中,我怎样才能对我的窗体中的所有文本框做些什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1499049/

相关文章:

.net - 从 .NET 应用程序执行 shell 命令

c# - 具有非唯一条目的两个列表之间的差异

c# - 使用 MySql 的 Entity Framework : Map System. VARCHAR(40) 指南

c# - 命名空间 'Device' 中不存在类型或命名空间名称 'System'

c# - 安装项目在安装过程中不创建文件系统文件夹

c# - 如何为两个 Windows 窗体应用程序共享一个 IsolatedStorage?

c# - 为什么这里的 TextRenderer.MeasureText 不准确?

c# - 嵌套数据读取器问题 mysql c#

c# - 使用 Vorbis 和 NAudio 播放 OGG 文件

c# - 具有相同路由前缀 ASP.NET Web Api 的多个 Controller 类型