2012-07-31 41 views

回答

2

1 - 設置用戶控件tag屬性。

2 - 將用戶控件添加到其父項。

3 - 通過迭代Control.Controls,獲取來自父級的Tag屬性的用戶控制權。

您的代碼應該是這樣的:

void AddControl(UserControl control, int id) 
{ 
    control.Tag = id; 
    this.panel.Controls.Add(control); 
} 

UserControl GetControl(int id) 
{ 
    foreach (Control control in this.panel.Controls) 
    { 
     if (id == (int) control.Tag) 
      return (UserControl) control; 
    } 
    return null; 
} 

// or using LINQ 
UserControl GetControl(int id) 
{ 
    return Controls.Cast<UserControl>() 
        .FirstOrDefault(control => id == (int) control.Tag); 
} 
+0

廣東話我做到這一點,而無需通過每個控制循環? – 2012-07-31 06:57:52

0

用戶控件也只是一個控件,因此它具有子控件的Controls屬性。用它。

參見herehere

相關問題