3
Answers

Creating user controls by name

gary_joynes

gary_joynes

20y
3.3k
1
How do you create a user control by name in code. Say I read in control names from a file. How do I then create them in code. In VB6 there was a CreateObject method but I can't find anything similar in C#
Answers (3)
0
gary_joynes

gary_joynes

NA 4 0 20y
I used the Activator class to create the user control by assembly name and user control namespace and name e.g. public static object CreateOject(string AssemblyPathName, string NamespaceClass) { Assembly assembly; //Can be used when instance in another assembly try { assembly;= Assembly.LoadFile(AssemblyPathName); } catch (System.IO.FileNotFoundException e) { throw an exception } System.Type TypeToCreate = assembly.GetType(NamespaceClass); if (TypeToCreate == null) { throw an exception; } return Activator.CreateInstance(TypeToCreate); } Note you don't have to create the assembly object if the type is part of the same assembly you can just get the Type by: Type TypeToCreate = Type.GetType(NamespaceClass);
0
Mykonine

Mykonine

NA 520 0 20y
The best way I can imagine to create controls while maintaining some degree of control over their names and accessing them by name would be to use some sort of data collection, maybe a hash set or ArrayList and search by the Name property when you want a specific control.
0
Mykonine

Mykonine

NA 520 0 20y
In C#, controls have a variable name and a control name. The variable name is the name you gave to the object in your code explicitly. The control name is a property in the control that you can change/check etc.