Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand first level children only of Treeview

Tags:

c#

treeview

I want to show all children of the first level on the treeview by default. And then expand all children of those on click.

like image 328
zsharp Avatar asked Dec 27 '11 19:12

zsharp


People also ask

How do I know if TreeView node is selected?

Solution 1 Use TreeView. SelectedNode[^] property, which get or set selected node for currently selected Treeview. If no TreeNode is currently selected, the SelectedNode property is a null reference (Nothing in Visual Basic).

How do you edit TreeView?

The TreeView allows you to edit nodes by setting the allowEditing property to true. To directly edit the nodes in place, double click the TreeView node or select the node and press F2 key. When editing is completed by focus out or by pressing the Enter key, the modified node's text saves automatically.


3 Answers

Try:

foreach (TreeNode tn in treeView1.Nodes) {
  tn.Expand();
}

When adding nodes during runtime, you can just check the level and expand, if needed:

private void ShouldAutoExpand(TreeNode tn) {
  if (tn.Level == 0)
    tn.Expand();
}

There is no NodeAdded event you can hook into to check that automatically. You would have to determine yourself whether or not a node should be expanded "by default".

Update:

From your comment, it seems like you want to have all level 0 nodes expanded, but then expand all child nodes of level 1 when you expand them.

Try subscribing to the BeforeExpand event with this code:

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) {
  treeView1.BeforeExpand -= treeView1_BeforeExpand;
  if (e.Node.Level == 1) {
    e.Node.ExpandAll();
  }
  treeView1.BeforeExpand += treeView1_BeforeExpand;
}
like image 190
LarsTech Avatar answered Oct 20 '22 02:10

LarsTech


you can try something like this.. you will have to change the example to fit your own code since you neglected to paste any code that you have or attempted

private void addChildNode_Click(object sender, EventArgs e) 
{
  var childNode = textBox1.Text.Trim();
  if (!string.IsNullOrEmpty(childNode)) {
    TreeNode parentNode = treeView2.SelectedNode ?? treeView2.Nodes[0];
    if (parentNode != null) {
      parentNode.Nodes.Add(childNode);
      treeView2.ExpandAll();
    }
  }
}
like image 1
MethodMan Avatar answered Oct 20 '22 01:10

MethodMan


if you want a recursive, try this:

void expAll(TreeNode node)
{
   node.Expand();
   foreach(TreeNode i in node.Nodes)
   {
       expAll(i);
   }
}
like image 1
Gustavo Maciel Avatar answered Oct 20 '22 01:10

Gustavo Maciel