How to create a Control given its type _as string_?

H

Helmut Giese

Hello out there,
de-serializing a collection of controls I have code like this to
recreate them:
Control ctrl;
switch (type) {
case "Button": ctrl = new Button(); break;
case "Label": ctrl = new Label(); break;
// and loads more of these
}
Surely there is a "generic" way to create controls given the type -
but I don't arrive at a solution.
Any hints will be greatly appreciated.
Best regards
Helmut Giese
 
J

Jeff Johnson

Hello out there,
de-serializing a collection of controls I have code like this to
recreate them:
Control ctrl;
switch (type) {
case "Button": ctrl = new Button(); break;
case "Label": ctrl = new Label(); break;
// and loads more of these
}
Surely there is a "generic" way to create controls given the type -
but I don't arrive at a solution.
Any hints will be greatly appreciated.

Look up "Activator.CreateInstance method".
 
I

Ignacio Machin

Hello out there,
de-serializing a collection of controls I have code like this to
recreate them:
    Control ctrl;
    switch (type) {
        case "Button": ctrl = new Button(); break;
        case "Label": ctrl = new Label(); break;
        // and loads more of these
    }
Surely there is a "generic" way to create controls given the type -
but I don't arrive at a solution.
Any hints will be greatly appreciated.
Best regards
Helmut Giese

You can use AppDomain.CreateInstance or better
Activator.CreateInstance , go and check the different parameters those
methods need.
 
H

Helmut Giese

Jeff and Ignacio,
thanks, this looks promising.
I see that there is a variant of CreateInstance which takes a string,
but (needed in a different context) a follow-up question:
How to go from a string "Button" to the type 'Button'?
Best regards
Helmut Giese
 
J

Jeff Johnson

thanks, this looks promising.
I see that there is a variant of CreateInstance which takes a string,
but (needed in a different context) a follow-up question:
How to go from a string "Button" to the type 'Button'?

Easy: don't use "Button"; ALWAYS use "System.Windows.Forms.Button".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top