building a treeview from an object graph (reflection)

R

Rein Petersen

Hi all,

I'm toying with reflection to try and build a recursive function that
generates treenodes of a treeview that represent any given object's
graph (of child objects):

public TreeNode BuildNode(ref object o)
{
TreeNode tn;
treenode.Tag = o;
treenode.Text = typeof(o).Name;

if (typeof(o).GetInterface("System.IEnumerable",true))
foreach (object c in o)
tn.Nodes.Add(BuildNode(ref c));
else
foreach(MemberInfo m in typeof(o).GetProperties(BindingFlags.Public))
tn.Add(BuildNode(ref mi.???); // << trouble here
// I really just want access
// to the property from the
// MemberInfo object...
return tn;
}

As you can see, it almost works except I have no way of accessing an
[un?]boxed object's property. I know from reflecting the object's type
that it has the property, but have no way of accessing the property (in
a generic manner) without hardcoding my object types into a bunch of
overloads of 'BuildNode', or having some way-huge switch.

Looking for advice, pointers to documents, creative ideas, etc. that
might get me closer to a solution.

Thanks for all your help,

Rein
 
M

Mattias Sjögren

public TreeNode BuildNode(ref object o)

Why is o passed by ref?

treenode.Text = typeof(o).Name;

That should probably be

treenode.Text = o.GetType().Name;

if (typeof(o).GetInterface("System.IEnumerable",true))

if ( o is IEnumerable )

foreach(MemberInfo m in typeof(o).GetProperties(BindingFlags.Public))
tn.Add(BuildNode(ref mi.???); // << trouble here

foreach(PropertyInfo p in
o.GetType().GetProperties(BindingFlags.Public))
if ( p.GetIndexParameters().Length == 0 )
tn.Add(BuildNode(p.GetValue(o, null)));



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top