Here is the code that worked for me:
public static Control CreateControl(string type, string name)
{
// Load the appropriate assembly from the GAC
Assembly winFormsAssembly =
Assembly.LoadWithPartialName("System.Windows.Forms ");
// Get the type
Type t = winFormsAssembly.GetType("System.Windows.Forms." + type, true);
// Get a constructor with no parameters
ConstructorInfo ci = t.GetConstructor(new Type[0]);
// Invoke the constructor
Control ctrl = (Control) ci.Invoke(null);
return ctrl;
}
"Jon Skeet [C# MVP]" wrote:
Shehab Kamal <Sh*********@discussions.microsoft.com> wrote: I would lik to instantiate the appropriate control/class given its name, such
as: Control c = new Control("TextBox") this should create a new TextBox().
I can write my own code that will create the appropriate control according
to the given name using switch statement, but I'm looking for a more elegant
solution using Type class or something like that.
Have a look at Type.GetType and Activator.CreateInstance.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too