Discussion:
Create a contol dynamically from string
(too old to reply)
x***@y.com
2016-08-25 06:04:23 UTC
Permalink
I want to add controls to a panel dynamically.
So normally:

TextBox textBox1 = new TextBox();
panel1.Controls.Add(textBox1);

But what if I know the control type as a string?
Like:

string controlType = "TextBox"; //or "Label" etc.

How can I create a control dynamically from the type given as string?
Marcel Mueller
2016-08-25 10:32:25 UTC
Permalink
Post by x***@y.com
I want to add controls to a panel dynamically.
TextBox textBox1 = new TextBox();
panel1.Controls.Add(textBox1);
But what if I know the control type as a string?
string controlType = "TextBox"; //or "Label" etc.
How can I create a control dynamically from the type given as string?
Then you need a factory function that creates the control for you.
Have a look at the Activator class to get an idea.

However, creating the control won't help you very much since you need to
know the exact type to populate the controls with appropriate data. So
in fact you factory needs to create /and/ fill the control with data.

Alternatively all of your controls need to share a common interface that
is used once the controls are created. Besides ITextControl the .NET
runtime does not provide helpful interfaces for this purpose. So this
usually implies to use custom controls with a custom interface.


Marcel
Stefan Ram
2016-08-25 15:57:56 UTC
Permalink
Post by x***@y.com
I want to add controls to a panel dynamically.
TextBox textBox1 = new TextBox();
panel1.Controls.Add(textBox1);
But what if I know the control type as a string?
string controlType = "TextBox"; //or "Label" etc.
How can I create a control dynamically from the type given as string?
public class Program
{
public static global::System.Windows.Controls.Control
get( string name )
{ global::System.Type type =
global::System.Type.GetType( name );
if( type != null )
return( global::System.Windows.Controls.Control )
global::System.Activator.CreateInstance( type );
foreach
( var assembly in
global::System.AppDomain.CurrentDomain.GetAssemblies() )
{ type = assembly.GetType( name );
if( type != null )
return( global::System.Windows.Controls.Control )
global::System.Activator.CreateInstance( type ); }
return null; }

[global::System.STAThread]
public static void Main()
{
{ global::System.Windows.Controls.Control control =
get( "System.Windows.Controls.TextBox" );
global::System.Console.WriteLine
( control.ToString() ); }

{ global::System.Windows.Controls.Control control =
get( "System.Windows.Controls.Label" );
global::System.Console.WriteLine
( control.ToString() ); }}}

Continue reading on narkive:
Loading...