【问题标题】:How can I access to a text box which is in a group box?如何访问组框中的文本框?
【发布时间】:2015-11-25 16:49:03
【问题描述】:

我设计了一个 Windows 窗体,它直接在窗体上放置了 textbox1,在 goupbox1 上放置了 textbox2。在代码下方运行只会更改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
    }
}

【问题讨论】:

    标签: c# winforms hierarchical


    【解决方案1】:

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

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

    【讨论】:

    • 亲爱的德米特里,您的回答正是我所需要的。但是没有足够的解释。您能详细解释一下您的解决方案吗?
    • 究竟有什么不清楚的地方?请提出具体问题,
    • 你能给我提供一些关键词来谷歌你的解决方法吗?
    猜你喜欢
    • 2017-08-09
    • 2014-05-03
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多