Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Reflection: Instantiate an object with string class name
    text
    copied!<p>my situation is the next: I'm working with Visual C# 2010 express developing a Windows Forms Application. When the user logins, dinamically build a menustrip with options loaded from a database table. In that table i save id, option name and Form Name.</p> <p>So, suppose that in my project i have a Form named Contabilidad, it has Contabilidad.cs that is the main class , so if i wanna create a new form and show it i do this:</p> <pre><code>Contabilidad frmConta = new Contabilidad(); frmConta.Show(); </code></pre> <p>But in this case, because the menu options are stored in database, in database i only have the string "Contabilidad". So, i want to use C# reflection to create a instance of Contabilidad or any other form only with class name in string format.</p> <p>First i tried this:</p> <pre><code>Form frmConta= (Form)Activator.CreateInstance(null, "Contabilidad").Unwrap(); </code></pre> <p>Because i read in a StackOverflow question that if i use null i'm referring to current assembly (my forms are all in the same project), but i get this message:</p> <pre><code>Could not load type 'Contabilidad' from assembly 'AccountingSA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. </code></pre> <p>The class definition is the next:</p> <pre><code>namespace AccountingSA { public partial class Contabilidad : Form { public Contabilidad() { InitializeComponent(); } ... </code></pre> <p>Also i tried this:</p> <pre><code>Assembly assembly = Assembly.Load("AccountingSA"); Type t = assembly.GetType("Contabilidad"); Form frmConta = (Form)Activator.CreateInstance(t); </code></pre> <p>But i get ArgumentNullException with this message:</p> <pre><code>Value cannot be null. Parameter name: type </code></pre> <p>Because t variable is null.</p> <p>What i'm do wrong? Thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload