I am trying to create a TreeNode with a key, but there is no constructor for TreeNode that takes a key and a text. I found only the following solutions:
TreeNode tn = new TreeNode("text node");
tn.Name = "keyNode";
treeView.Nodes.Add("keyNode", "text node");
But those ways do not suit me, as I am trying to add new TreeNodes to my treeView with a Linq query.
Here is what I would like to do ideally:
treeView.Nodes.AddRange(
myListOfObject.Select(x => new TreeNode(x.somePropertyForKey,
x.somePropertyForText)).
ToArray<TreeNodes>());
Am I stuck to use a foreach loop to create the TreeNodes or do you see a way to do this one-line-ish?
Thats what the new initialization syntax is for
TreeNode tn = new TreeNode("text node") {Name = "keynode"} ;
treeView.Nodes.AddRange(myListOfObject.Select(new TreeNode
{
Name = "keyNode",
TreeNode = new TreeNode[]{new TreeNode{Name="text node"}}}
});
Should be something like that. (Please check the braces and syntax)
You would want to use this constructor TreeNode(String, TreeNode[])
BTW, if that does not work and you are not hitting a database, you can do just the following:
treeView.Nodes.AddRange(myListOfObject.Select(new TreeNode
(
"keyNode",
new TreeNode[]{new TreeNode{Name="text node"}}}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With