[英]Find a control in Windows Forms by name
我正在開發一個應用程序,它在運行時從 XML 文件添加對象(基本上是Windows 窗體控件)。 應用程序需要訪問已添加的對象。
對象被添加到面板或分組框中。 對於面板和分組框,我有 Panel.Controls["object_name"] 來訪問對象。 這僅在對象直接添加到同一面板上時才有用。 在我的例子中,主面板 [pnlMain,我只能訪問這個面板] 可能包含另一個面板,這個面板 [pnlChild] 再次包含一個 groupbox[gbPnlChild] 並且 groupbox 包含一個按鈕 [button1,我想訪問這個按鈕] . 我有以下方法:
Panel childPanel = pnlMain.Controls["pnlChild"];
GroupBox childGP = childPanel.Controls["gbPnlChild"];
Button buttonToAccess = childGP["button1"];
當父母知道時,上述方法是有幫助的。 在我的場景中,只知道要訪問的對象的名稱 [button1] 而不是其父對象。 那么我如何通過它的名稱訪問這個對象,而與它的父對象無關?
有沒有像 GetObject("objName") 或類似的方法?
您可以使用表單的Controls.Find()方法來檢索引用:
var matches = this.Controls.Find("button2", true);
請注意,這將返回一個數組,控件的 Name 屬性可能不明確,沒有確保控件具有唯一名稱的機制。 你必須自己強制執行。
如果您在用戶控件中並且不能直接訪問容器表單,則可以執行以下操作
var parent = this.FindForm(); // returns the object of the form containing the current usercontrol.
var findButton = parent.Controls.Find("button1",true).FirstOrDefault();
if(findButton!=null)
{
findButton.Enabled =true; // or whichever property you want to change.
}
TextBox txtAmnt = (TextBox)this.Controls.Find("txtAmnt" + (i + 1), false).FirstOrDefault();
當您知道自己在尋找什么時,這會起作用。
.NET Compact Framework 不支持 Control.ControlCollection.Find。
請參閱Control.ControlCollection 方法並注意 Find 方法旁邊沒有小電話圖標。
在這種情況下,定義以下方法:
// Return all controls by name
// that are descendents of a specified control.
List<T> GetControlByName<T>(
Control controlToSearch, string nameOfControlsToFind, bool searchDescendants)
where T : class
{
List<T> result;
result = new List<T>();
foreach (Control c in controlToSearch.Controls)
{
if (c.Name == nameOfControlsToFind && c.GetType() == typeof(T))
{
result.Add(c as T);
}
if (searchDescendants)
{
result.AddRange(GetControlByName<T>(c, nameOfControlsToFind, true));
}
}
return result;
}
然后像這樣使用它:
// find all TextBox controls
// that have the name txtMyTextBox
// and that are descendents of the current form (this)
List<TextBox> targetTextBoxes =
GetControlByName<TextBox>(this, "txtMyTextBox", true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.