I am doing a foreach loop where I add nodes to a treeview control. When
TreeNode treeNode;
foreach (Item item in stuff)
{
treeNode = this.TreeView.Nodes.Add("label");
}
What I want to do is put a conditional in the loop that, if true, it adds any following nodes in the loop as child nodes to that treeNode where the conditional is true. I can do this for a single occurence where the conditional is true, but how can I do it if it is true WITHIN a node that is already a child? Ie. make a child node of a child node of a child node and so on... instead of doing it manually like Nodes.Nodes.Nodes.Nodes. etc...
Thanks
Loading
giangurgoloPosted Jan 27, 2008, 1:10 PM
Matthew CochranPosted Jan 26, 2008, 10:34 AM
You are probably using Studio2005 and .NET 2.0 so you don't have lambda expressions available. You can use an anonymous delegate like this:
ModifyCollection(tv.Nodes, delegate(TreeNodeCollection c)
{
if (c.Count == 4) // test
c.Add("SAMPLE TEXT"); // add items here based on conditions
});
or you can explicitly define the method:
private void DoSomethingTo(TreeNodeCollection c)
{
if (c.Count == 4) // test
c.Add("SAMPLE TEXT"); // add items here based on conditions
}
And call it like this:
ModifyCollection(tv.Nodes, DoSomethingTo);
They are all different ways to do the same thing. Let me know if these worked for you.
-Matt
giangurgoloPosted Jan 25, 2008, 6:23 PM
Here is my code:
private void InitializeScriptEditor()
{
this.ScriptTree.Nodes.Clear();
TreeNode treeNode;
foreach (ScriptCommand bsc in commands)
{
treeNode = this.ScriptTree.Nodes.Add("whatever");
if (bsc.CommandID == 0xFC)
; // add the nodes as child nodes here
}
}
Once again, thanks for the help.
Matthew CochranPosted Jan 25, 2008, 2:58 PM
private void ModifyCollection(TreeNodeCollection c, Action<TreeNodeCollection> visitor)
{
visitor(c);
foreach (TreeNode node in c)
ModifyCollection(node.Nodes, visitor);
}
You could recursively go through each collection and add nodes based on some condition (you can use a anonymous delegate as in the following code or create a seperate method to handle the test and adding of nodes that is supposed to be repeated).
TreeView tv = new TreeView();
ModifyCollection(tv, collection =>
{
if (collection.Count == 4) // test
collection.Add("SAMPLE TEXT"); // add items here based on conditions
});
You could use the same technique to go through the Nodes instead of the collections (define a recursive method with a Node as input parameter instead of the collection).