[英]C# winform, Can I access Controls Inside a GroupBox like this: myGroupBox.InnerTextBox.Text “someText”;?
我有一個具有3個TextBoxes
和3 Labels
的GroupBox
,該組框的名稱是TextInfoGroupBox ..我正試圖訪問其中的textBoxes,但我似乎不知道如何..我嘗試了以下操作:
TextInfoGroupBox.innerTextbox;
TextInfoGroupBox.Controls.GetChildControl;
兩者都沒有在智能中彈出。我如何到達它們,設置它們並從中獲取數據?
您可以像訪問其他任何控件一樣訪問它們:
innerTextBox
無論嵌套如何,Visual Studio設計器都會為您放入表單的每個控件生成一個字段。
為此使用Controls
集合。 您將需要確切地知道該集合中的哪個項目是您的TextBox。 如果您的組框中只有3個文本框,則可以使用
groupBox.Controls[0], groupBox.Controls[1], groupBox.Controls[2]
訪問您的商品或僅使用它們各自的名稱。
如果由於某種原因無法直接訪問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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.