Reputation: 22076
Frist see following code and images.
Code A
treeView1.Nodes.Add("Node A");
treeView1.Nodes.Add("Node B");
Output :
Code B
TreeNode tn = new TreeNode();
tn.Nodes.Add("Node A");
tn.Nodes.Add("Node B");
treeView1.Nodes.Add(tn);
Now my problem is that treeView1.Nodes.Add(tn);
creating a blank node, but my requirement is like Code A's
image type (without blank node). If you need any other information please let me know.
UPDATE
Actually Ithere is a function in my code which returns a TreeNode
and I have to add this node to TreeView
control without first blank level.
Upvotes: 2
Views: 1948
Reputation: 22719
This code:
TreeNode tn = new TreeNode();
creates an actual item. You didn't give it any text, so it appears blank. Then next two lines are adding child nodes to the blank node.
If your goal is the code in "A", why are you writing "B"?
Edit: response to your updated question
You have a function returning a root blank tree node, which contains children you want. So, something like this is in order.
foreach (var node in returnedNode.Nodes)
{
treeView1.Nodes.Add(node);
}
OR
treeView1.Nodes.AddRange(returnedNode.Nodes.Cast<TreeNode>().ToArray());
Upvotes: 5
Reputation: 62494
Name of the root node is empty because you've used default constructor of the TreeNode class.
Try out specifying name for the tn
node using TreeNode(string text) constructor
// specify name of the root node
TreeNode tn = new TreeNode("Root Node Name");
tn.Nodes.Add("Node A");
tn.Nodes.Add("Node B");
treeView1.Nodes.Add(tn);
UPDATE: Since question was updated
Just set Text
property for node returned by a function:
TreeNode treeNode = YourMethodWhichCreatesTreeNode();
treeNode.Text = "Root Node Name";
treeView.Nodes.Add(treeNode);
Upvotes: 2
Reputation: 48230
TreeNode t1 = new TreeNode( "Node A" );
treeView1.Nodes.Add( t1 );
TreeNode t2 = new TreeNode( "Node B" );
treeView1.Nodes.Add( t2 );
You have to add nodes directly UNDER treeView1
, not under it's child as in 2nd snippet.
Upvotes: 2