How to add more values to a TreeNode class in C#
A TreeNode class has
Text Name Tag
I need to assign more values to a TreeNode class like float1, float2, ..开发者_开发百科. float6.
How can I do this??? pls help.
Thx, Caslav
You can create a new class which inherits the TreeNode. For each value you want to store in the treenode, create a property for that value. When working with the Treeview, simply cast the TreeNode to your custom TreeNode class.
Example:
public class JobTreeNode : TreeNode {
private int intField1;
public int Field1 {
get {
return intField1;
}
set {
intField1 = value;
}
}
}
Usage (added after comments)
// Add the node
JobTreeNode CustomNode = new JobTreeNode();
CustomNode.Text = "Test";
CustomNode.Field1 = 10
treeView1.Nodes.add(CustomNode);
// SelectedNode
((CustomNode)(treeView1.SelectedNode)).Field1;
The Tag property of TreeNode is "object". Can't you just store your data in there using a dataclass of some kind?
You can create a lightweight class to hold your float1..6 and put an instance in the Tag property.
Alternatively, you can use a Dictionary<TreeNode, FloatsClass>
or maybe use 6 separate Dictionary<TreeNode, float>
.
Note that dotNet 4 has a new Tuple<A,B,C,...>
type to make this kind of situations a little easier.
You could have:
class TreeNodeProperties
{
public float Float1 { get; set;}
public float Float2 { get; set;}
public float Float3 { get; set;}
public float Float4 { get; set;}
public float Float5 { get; set;}
public float Float6 { get; set;}
}
Then set the Tag property on your TreeNode:
var properties = new TreeNodeProperties()
{
Float1 = 10,
Float2 = 20,
Float3 = 30,
Float4 = 40,
Float5 = 50,
Float6 = 60
}
myTreeNode.Tag = properties;
To read the properties:
var nodeproperties = TreeViewMyTree.SelectedNode.Tag as TreeNodeProperties;
MessageBox.Show("Float5: "+nodeproperties.Float5);
精彩评论