Friday, May 6, 2011

How can I programmatically click a TreeView TreeNode so it appears highlighted in the list and fires the AfterSelect event?

I have a TreeView control in a Winforms app, and basically the objective is to display a form that contains a TreeView control, and I want to display the form with a node opened (easy - EnsureVisible) and selected.

The problem that I'm running into is that when I set the TreeView control's SelectedNode property, the node isn't highlighted and the AfterSelect event isn't firing as I would expect it to. The AfterSelect thing is easy to code around, but the lack of highlighting is annoying.

From stackoverflow
  • After you set the SelectedNode. Try selecting the treeView. Worked for me anyway.

    private void button1_Click(object sender, EventArgs e)
    {
    this.treeView1.SelectedNode = this.treeView1.Nodes[1];
    this.treeView1.Select();
    }
    
    Joh : this.treeView1.Select() had no effect for me. Setting HideSelection to false did the trick, though.
  • Is it because the TreeView doesn't have focus? Does setting the TreeView's HideSelection property to False change the behavior you're seeing?

  • By highlighting, I am assuming you mean to make the text bold. It's not as elegant as some of the other client side technologies, but you could handle the node being changed and make the selected node bold with something like

    treeNode.Font = new Font(treeNode.Font, treeNode.Font.Style | treeNode.Bold);
    

0 comments:

Post a Comment