Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a control in Windows Forms by name

I am working on an application which add objects (basically Windows Forms controls) at run time from an XML file. The application needs to access the objects that have been added.

The objects are added in a panel or in a groupbox. For the panel and groupbox, I have Panel.Controls["object_name"] to access the objects. This is only helpful when the object is directly added on the same panel. In my case the main panel [pnlMain, I have access to this panel only] may contain another panel and this panel [pnlChild] again contains a groupbox[gbPnlChild] and the groupbox contains a button [button1, I want to access this button]. I have the following method for this:

Panel childPanel = pnlMain.Controls["pnlChild"];
GroupBox childGP = childPanel.Controls["gbPnlChild"];
Button buttonToAccess = childGP["button1"];

The above method is helpful when parents are known. In my scenario, only the name of the object is known that is to be accessed [button1] and not its parents. So how do I access this object by its name, irrelevant of its parent?

Is there a method like GetObject("objName") or something similar?

like image 956
Vinod Maurya Avatar asked Dec 19 '10 16:12

Vinod Maurya


1 Answers

If you are in a user control and don't have direct access to container form you can do the following

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.
}
like image 137
Shashank Shekhar Avatar answered Sep 24 '22 07:09

Shashank Shekhar