Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll selected TreeView node into view

Tags:

I have a System.Windows.Forms.TreeView docked inside a panel. I am setting a node selected programmatically. What method or property would I use to have the treeview scroll the selected into view?

like image 974
Brad Avatar asked Jan 19 '09 15:01

Brad


3 Answers

node.EnsureVisible();

for example:

if(treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible();

(see MSDN)

like image 189
Marc Gravell Avatar answered Sep 27 '22 00:09

Marc Gravell


I also had issues with this and figured out that treeview.ExpandAll() ignores the EnsureVisible() effect and avoids the scrolling to the node position.

Just call EnsureVisible() after ExpandAll() if you want a full expanded tree with the scroll on the node you've selected.

like image 1
Folkien Avatar answered Sep 27 '22 00:09

Folkien


To ensure the visibility of selected item:

private void EnsureItemVisible()
{
    if(treeView1.SelectedNode == null)
    {
        return;
    }

    for (int i = treeView1.SelectedNode.Index + treeView1.VisibleCount / 2; i >= 0; i--)
    {
        if (treeView1.Nodes.Count > i && treeView1.Nodes[i] != null)
        {
            treeView1.Nodes[i].EnsureVisible();
            break;
        }
    }

    for (int i = treeView1.SelectedNode.Index - treeView1.VisibleCount / 2; i < treeView1.Nodes.Count; i++)
    {
        if (i >= 0 && treeView1.Nodes[i] != null)
        {
            treeView1.Nodes[i].EnsureVisible();
            break;
        }
    }
}

Handle the TreeView selection has been changed:

private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
{   
    EnsureItemVisible();
}
like image 1
Joaquim Varandas Avatar answered Sep 27 '22 00:09

Joaquim Varandas