Accessing object properties from a treenode that's associated with it?

喜你入骨 提交于 2021-02-05 07:54:09

问题


Hallo, I have read Easy object binding to Treeview Node, but still have unanswered question.

if an object is associated with treenode tag property, how to access that object members/properties from that treenode ?


node1 = new TreeNode();
node1.tag = object1;
//ex:if object1 has public property valueA
//How to access valueA  from node1 ??

回答1:


Maybe you can cast it back to the object1 type...

var valueA = ((object1Type)node1.tag).valueA;



回答2:


MyClass c = treeNode.Tag as MyClass;
theValue = c.TheProperty;

If you don't know the type of the object in question, then you can use System.Reflection:

System.Reflection.PropertyInfo pi = treeNode.Tag.GetType().GetProperty("SomeName");
theValue = pi.GetValue(treeNode.Tag, null);

Finally, if you want to know the names of the properties, again System.Reflection to the rescue:

System.Reflection.PropertyInfo[] pis = treeNode.Tage.GetType().GetProperties();
foreach (var pi in pis) {
  theName = pi.Name;
}


来源:https://stackoverflow.com/questions/2986999/accessing-object-properties-from-a-treenode-thats-associated-with-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!