By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,978 Members | 1,831 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,978 IT Pros & Developers. It's quick & easy.

Creating Classes by name

P: n/a
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.
Thanks in advance,
Shehab.
Feb 1 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Feb 1 '06 #2

P: n/a
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

Feb 5 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.