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?
node.EnsureVisible();
for example:
if(treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible();
(see MSDN)
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With