4

How to add nodes dynamically to a already existing treeview?

if an example as,

-Root
  -child1

above one is already existing treeview. but i want to add one more node(child2) to the Root, output is like..

-Root
  -child1
  -child2
2
  • winforms, asp.net, javascript? Commented Jun 8, 2011 at 14:42
  • 1
    No, it's not obvious. You have a treecontrol in asp.net. You can use javascript/jquery in ASP.NET MVC to modify a treeview. So be more polite next time since it's you and not me that need help. Commented Jun 8, 2011 at 14:45

4 Answers 4

4

Try this:

TreeNode rootNode = TreeView.Nodes.Cast<TreeNode>().ToList().Find(n => n.Text.Equals("Root"));
if (rootNode != null)
{
    rootNode.Nodes.Add("child2");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response perfect one but it gives the error as "an object reference is required for a non-static field,method or property 'System.Windows.Forms.TreeView.Nodes.Get' "
Did you replace the TreeView with the name of your treeView?
3

try:

treeView1.Nodes.Add(new TreeNode())

Details are found here: http://msdn.microsoft.com/de-de/library/system.windows.forms.treeview.nodes.aspx

2 Comments

thanx, but that "Root" is already generated in intializecomponent(),how can we use it actual program.
if its autogenerated, try treeView1.TopNode to access the treeviews root node or treeView1.Nodes to access the nodes collection. It comes with the Add() method. Please note, in Stackoverflow, the way of saying 'thanks' is to upvote an answer, if it is usefull to you ;)
1

I am assuming you are referring to the asp.net TreeView control

MyTreeView.Nodes.Add(new TreeNode() { Text = "Child 2" });

1 Comment

I am not a winforms guy but from looking at the MSDN article for the winforms TreeView it would work for that too. Esentially the root nodes are the nodes collection on the TreeView and you just need to a node to it.
1

There are three ways to control a control like a tree view:

  1. Declaratively add values in tags - not an option here
  2. Bind all rows programatically - you can do this, but it is overkill
  3. Add items afterward TreeviewName.Nodes.Add()
  4. Add to the bound data set

If you are going to have to have the same treeview either a) appear to multiple people or b) reconsitute after postbacks, I actually like massaging and caching the dataset and binding. It is rather simple and lighter weight than the other options if it is being reused.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.