c# - 如何访问组框中的文本框?

标签 c# winforms hierarchical

我设计了一个 Windows 窗体,将 textbox1 直接放置在窗体上,将 textbox2 放置在 goupbox1 上。运行下面的代码只会更改 textbox1 的文本。我用谷歌搜索了很多,但找不到解决方案。我怎样才能到达textbox2

public Form1()
{
    InitializeComponent();
    foreach (TextBox txtBox in this.Controls.OfType<TextBox>())
    {
        txtBox.Enter += textBox_Enter;
        txtBox.Text = "123"; //To test if the text box is recognized or not
    }
}

最佳答案

您可以使用递归。
我建议您使用以下扩展方法:

public static IEnumerable<T> GetAllControls<T>(Control control)
{
    var controls = control.Controls.OfType<T>();
    return control.Controls.Cast<Control>()
        .Aggregate(controls, (current, c) => current.Concat(GetAllControls<T>(c)));
}

用法:

var textBoxes = GetAllControls<TextBox>(this);

关于c# - 如何访问组框中的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32314850/

相关文章:

c# - 如果我不收集垃圾,为什么服务器垃圾收集速度更快?

php - 使用更新的值复制同一表中的分层 SQL 数据

c# - 将 QueryString ID 从 aspx 页面传递到 winform 文本框

winforms - F#:尝试打开 System.Windows.Forms 时未定义命名空间

c# - 如何使用 windowhook 模拟按键

xml - XStream反序列化具有分层对象列表的xml

php - 是否有PHPUnit的分层测试运行器?

c# - Controller 上的 ActionFilterAttribute 与操作方法

c# - 无法从 NUnit 单元测试打印

c# - Excel 和 XML 文件之间的映射 - 如何从 C# 刷新