C#winform,我可以像这样访问GroupBox内的控件:myGroupBox.InnerTextBox.Text“someText”;?

时间:2012-07-24 16:38:59

标签: c# winforms

我有一个GroupBox,其中包含3 TextBoxes和3 Labels 组框的名称是TextInfoGroupBox .. 我正在尝试访问其中的textBoxes,但我似乎并不知道如何... 我试过像:

TextInfoGroupBox.innerTextbox;
TextInfoGroupBox.Controls.GetChildControl;

这两个都没有出现在intellisence .. 我如何联系他们,设置并从中获取数据?

3 个答案:

答案 0 :(得分:2)

您可以像任何其他控件一样访问它们:

innerTextBox

Visual Studio设计器为您放入表单中的每个控件生成一个字段,无论嵌套如何。

答案 1 :(得分:1)

为此目的使用Controls集合。您需要确切知道该集合中的哪个项目是您的TextBox。如果您的组框中只有3个文本框,则可以使用

groupBox.Controls[0], groupBox.Controls[1], groupBox.Controls[2]

访问您的商品或只使用各自的名称。

答案 2 :(得分:0)

如果由于某种原因无法直接访问innerTextBox,您可以随时寻找:

        TextBox myTextBox = null;

        Control[] controls = TextInfoGroupBox.Controls.Find("InnerTextBoxName", true);
        foreach (Control c in controls)
        {
            if (c is TextBox)
            {
                myTextBox = c as TextBox;
                break;
            }
        }

最后,如果myTextBox为null,则无法找到它(显然)。希望你不要构造它以便有多个条目。

您还可以创建一些可爱的扩展方法:

public static Control FindControl(this Control parent, string name)
{
    if (parent == null || string.IsNullOrEmpty(name))
    {
        return null;
    }

    Control[] controls = parent.Controls.Find(name, true);
    if (controls.Length > 0)
    {
        return controls[0];
    }
    else
    {
        return null;
    }
}

public static T FindControl<T>(this Control parent, string name) where T : class
{
    if (parent == null || string.IsNullOrEmpty(name))
    {
        return null;
    }

    Control[] controls = parent.Controls.Find(name, true);
    foreach (Control c in controls)
    {
        if (c is T)
        {
            return c as T;
        }
    }

    return null;
}

你可以简单地将它们称为

        Control c = TextInfoGroupBox.FindControl("MyTextBox");
        TextBox tb = TextInfoGroupBox.FindControl<TextBox>("MytextBox");