kik
kik

Reputation: 247

How to add nodes to a treeview programatically?

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

Upvotes: 4

Views: 16179

Answers (4)

Alex Mendez
Alex Mendez

Reputation: 5150

Try this:

TreeNode rootNode = TreeView.Nodes.Cast<TreeNode>().ToList().Find(n => n.Text.Equals("Root"));
if (rootNode != null)
{
    rootNode.Nodes.Add("child2");
}

Upvotes: 4

user492238
user492238

Reputation: 4084

try:

treeView1.Nodes.Add(new TreeNode())

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

Upvotes: 3

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

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.

Upvotes: 1

Coding Flow
Coding Flow

Reputation: 21881

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

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

Upvotes: 1

Related Questions