Search code examples
c#winformstreeview

How to select a node of treeview programmatically in c#?


Used treeview.SelectedNode to select a child node. How to invoke treeview.AfterSelect event when a node is selected programmatically?

this.treeView1.SelectedNode = this.treeView1.Nodes[0].Nodes[0].Nodes[0].Nodes[0]; 
if (this.treeView1.Nodes[0].Nodes[0].Nodes[0].Nodes[0].IsSelected) 
{
 MessageBox.Show("Node is selected"); 
}

Solution

  • Apologies for my previously mixed up answer.

    Here is how to do:

    myTreeView.SelectedNode = myTreeNode;
    

    (Update)

    I have tested the code below and it works:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            treeView1.Nodes.Add("1", "1");
            treeView1.Nodes.Add("2", "2");
            treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
            TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
            treeView1.SelectedNode = treeNode;
            MessageBox.Show(treeNode.IsSelected.ToString());
        }
    
    
    }