![]() |
|
|
#1 |
|
Hardcore Monkey Moderator
Join Date: Feb 2007
Location: Cheeseland (Wisconsin, USA)
Posts: 12,254 (5.27/day)
Thanks: 591
Thanked 5,510 Times in 2,948 Posts
|
C# Tips : Instantiation of Forms by name through reflection
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 ... Code:
using System.Reflection; using System.Reflection.Emit; Code:
private void GenerateTreeViewNodes()
{
TreeNode _RootNode, _ChildNode;
string[] _Forms = new string[] { "Form1", "Form2", "Form3" };
Assembly _Assembly = Assembly.GetExecutingAssembly();
for (int i = 0; i < _Forms.Length; i++)
{
Form _Form = (Form)_Assembly.CreateInstance("myNamespace." + _Forms[i]);
_Node = new TreeNode(_Forms[i]);
_Node.Name = _Forms[i];
myTreeView.Nodes.Add(_Node);
foreach (Control _c in _Form.Controls)
{
if (_c.GetType().ToString().Contains("Button"))
{
_Child = new TreeNode(c.Name);
_Child.Name = c.Name;
_Node.Nodes.Add(_Child);
}
}
_Form.Dispose();
}
}
Happy Coding !! Disclaimer : There could be syntax errors. My actual code is a little different.
__________________
Cloud (noun, singular): A dynamic arrangement of multiple potential single points of failure, with a user at one end and their data at the other. Get more tech news on a wide variety of topics at NextPowerUp
|
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Take-Two Forms New Release Dates, Announces Bioshock 2 is in the Works | malware | News | 5 | Mar 12, 2008 02:29 PM |
| [Case Gallery] Inner Reflection | Sir Stunna Lot | Case Mod Gallery | 11 | Dec 29, 2007 09:30 PM |
| Acer Forms Low-price PC Team | malware | News | 3 | Nov 23, 2007 08:42 PM |
| Activision Forms Partnership with Audiokinetic | malware | News | 0 | Oct 25, 2007 02:00 PM |
| EA Forms Jet Black Games Console Subdivision | malware | News | 5 | Apr 18, 2007 12:06 PM |