How to create a Control given its type _as string_?

  • Thread starter Thread starter Helmut Giese
  • Start date Start date
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
 
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".
 
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.
 
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
 
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".
 
Back
Top