Converting  string to the object  it represent

yaron89
yaron89 used Ask the Experts™
on
In my winform app I keep object name as string in order to add control to this object later.
String ObjectName="picListContainer.Panel2"
How do I convert this string to the object  it represent ?

this is the result I need
picListContainer.Panel2.Controls.Add(TabControl1);
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dirk HaestProject manager

Commented:
I think that you need reflection.
Take a look at the following article

Creating objects dynamically with C# 2.0
http://blog.benhall.me.uk/2006/08/creating-objects-dynamically-with-c-20.html
Hi,

are you always doing this with Panels? Or is it a whole range of controls?

J
Dirk HaestProject manager

Commented:
Following snippet found at :
How to create instance of class from string?
http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=32187
The simplest way of doing this should be as follows 
 
using System.Reflection; 
 
 
private Control myControl createNewControl(string controlToCreate) 
{ 
 
try 
{ 
// create a new control 
Control myControl = new Control(); 
 
 
//Define the type of the control you want to create an instance of using reflection. 
 
Type typeofControl = Type.GetType(controlToCreate,true); 
 
myControl = (Control)(Activator.CreateInstance(typeofControl)); 
} 
catch 
{ 
//Set the control to null 
myControl = null; 
} 
 
return myControl; 
} 
 
 
 
//This would the be called using the following code 
Control myControl = new Control(); 
myControl = createNewPanel ("MyProject.Classes.MyClass"); 

Open in new window

Author

Commented:
Hi Dhaest

I dont have to create new Instance. The ObjectName string is the name of allready exist instance that I want to add some control to it.
Thank You
Thank You
Project manager
Commented:
So you need to find a control ...

Dim ctrls() As Control = Me.Controls.Find("TextBox1", True)

Finding Controls on Forms
http://msmvps.com/blogs/deborahk/archive/2009/07/27/finding-controls-on-forms.aspx

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial