Link to home
Start Free TrialLog in
Avatar of yaron89
yaron89

asked on

Converting string to the object it represent

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);
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

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
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

Avatar of yaron89
yaron89

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial