2010-12-19 21 views
7

我正在處理一個應用程序,該應用程序在運行時從XML文件添加對象(基本上爲Windows Forms控件)。應用程序需要訪問已添加的對象。按名稱在Windows窗體中查找控件

對象添加在面板或組框中。對於panel和groupbox,我有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」)或類似的方法?

回答

24

您可以使用窗體的Controls.Find()方法來檢索參考回:

 var matches = this.Controls.Find("button2", true); 

要注意的是這個返回陣列,控件的名稱屬性可以是不明確的,沒有機制保證一個控件有一個唯一的名字。你必須自己執行。

+1

該不會在.NET Compact Framework的工作。 – 2013-09-28 06:10:05

+0

這是一個區分大小寫的搜索嗎? – 2017-03-01 19:09:56

1

.NET Compact Framework不支持Control.ControlCollection.Find。

請參閱Control.ControlCollection Methods並注意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); 
3
TextBox txtAmnt = (TextBox)this.Controls.Find("txtAmnt" + (i + 1), false).FirstOrDefault(); 

這工作時,你知道你正在尋找熱塑成型的東西。

+0

表達式中的+1將我從一個bug中拯救出來! – shipr 2015-08-09 15:30:29

2

如果你是在用戶的控制和沒有容器的形式直接進入,你可以做以下

var parent = this.FindForm(); // returns the object of the form containing the current usercontrol. 
var findButton = parent.Controls.Find("button1",true).FirstOfDefault(); 
if(findButton!=null) 
{ 
    findButton.Enabled =true; // or whichever property you want to change. 
}