Rev
Rev

Reputation: 2275

Convert string to Control Type in C#?

I have string property and Fill it with This Code :

  prop1= MyCustomPanle.GetType().ToString(); 

I use prop1 to keep type of Controls(wpf base control's and custom control's) .I keep this property and want to create type base on value this property. Something like This:

  Type ControlType=Type.Gettype(prop1); 

But this Type.GetType() work only for variable type like int, string, etc.

How convert string to control type?

Upvotes: 0

Views: 2450

Answers (2)

Tyson
Tyson

Reputation: 14734

You need to pass in the full AssemblyQualifiedName into GetType().

You can get this from calling GetType().AssemblyQualifiedName on an existing instance of the type you want.

e.g.

var myControlTypeName = typeof(MyControl).AssemblyQualifiedName;
var myControlType = Type.GetType(myControlTypeName);

myControlTypeName above ends up as:

MyNamespace.MyControl, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

But if you want it to be version neutral I beleive it can be shorted to the below and still work:

MyNamespace.MyControl, MyProject

Upvotes: 2

zmbq
zmbq

Reputation: 39029

I think you're looking for Activator.CreateInstance, this will create an object based on a type known only at runtime: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Upvotes: 2

Related Questions