# C# Tips : Instantiation of Forms by name through reflection



## Kreij (Feb 28, 2010)

I haven't written any tips lately as I've been busy coding, so I figured it's time to share a little knowledge.

I have an app that has many Forms. What I needed was a way to generate a "Checked" TreeView that contained the Forms as root level nodes, and each Form's buttons as child nodes of their respective root nodes (in my case, for user access control based on the checked value of the TreeView node).

The problems : 
1) I don't want to have to hard code everything. I'm lazy. 
2) I don't want to have to code an instantiation of each form by it's type (ig. Form1 _Form = new Form1()). I'm still lazy. 
3) I don't want to instantiate all of the Forms at once and gobble up a ton of memory.

So here we go ... (this little example uses 3 Forms and assumes you have a TreeView on the Form this is running on)

Start by adding ...

```
[COLOR="Blue"]using[/COLOR] System.Reflection;
[COLOR="Blue"]using[/COLOR] System.Reflection.Emit;
```

Now add a method to create the TreeView nodes ...

```
[COLOR="Blue"]private void[/COLOR] GenerateTreeViewNodes()
{
    [COLOR="MediumTurquoise"]TreeNode[/color] _RootNode, _ChildNode;
    
    [COLOR="Blue"]string[/COLOR][] _Forms = [COLOR="blue"]new string[/COLOR][] { [COLOR="Red"]"Form1"[/COLOR], [COLOR="red"]"Form2"[/COLOR], [COLOR="red"]"Form3"[/COLOR] };

    [color="MediumTurquoise"]Assembly[/color] _Assembly = [color="MediumTurquoise"]Assembly[/color].GetExecutingAssembly();

    [COLOR="Blue"]for[/COLOR] ([COLOR="blue"]int[/COLOR] i = 0; i < _Forms.Length; i++)
    {
        [COLOR="MediumTurquoise"]Form[/COLOR] _Form = ([COLOR="mediumturquoise"]Form[/COLOR])_Assembly.CreateInstance([COLOR="Red"]"myNamespace."[/COLOR] + _Forms[i]);
        _Node = [COLOR="blue"]new[/COLOR] [COLOR="MediumTurquoise"]TreeNode[/COLOR](_Forms[i]);
        _Node.Name = _Forms[i];
        myTreeView.Nodes.Add(_Node);

        foreach ([COLOR="MediumTurquoise"]Control[/COLOR] _c [COLOR="Blue"]in[/COLOR] _Form.Controls)
        {
            if (_c.GetType().ToString().Contains([color="Red"]"Button"[/color]))
            {
                _Child = [COLOR="Blue"]new[/COLOR] [COLOR="MediumTurquoise"]TreeNode[/COLOR](c.Name);
                _Child.Name = c.Name;
                _Node.Nodes.Add(_Child);
             }
        }
        _Form.Dispose();
    }
}
```

There you have it. I hope someone finds it useful.
Happy Coding !!

*Disclaimer : There could be syntax errors. My actual code is a little different.*


----------

