Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"); 
}
like image 310
user186246 Avatar asked Jan 17 '11 12:01

user186246


People also ask

How do you find a node in TreeView?

Use the FindNode method to get a node from the TreeView control at the specified value path. The value path contains a delimiter-separated list of node values that form a path from the root node to the current node. Each node stores its value path in the ValuePath property.

How do I know if TreeView node is selected?

Solution 1Use 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).

What is TreeView node?

The Nodes property holds a collection of TreeNode objects, each of which has a Nodes property that can contain its own TreeNodeCollection. This nesting of tree nodes can make it difficult to navigate a tree structure, but the FullPath property makes it easier to determine your location within the tree structure.


2 Answers

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());     }   } 
like image 190
Aliostad Avatar answered Oct 04 '22 03:10

Aliostad


treeViewMain.SelectedNode = treeViewMain.Nodes.Find(searchNode, true)[0]; 

where searchNode is the name of the node. I'm personally using a combo "Node + Panel" where Node name is Node + and the same tag is also set on panel of choice. With this command + scan of panels by tag i'm usually able to work a treeview+panel full menu set.

like image 32
Daniele Pistollato Avatar answered Oct 04 '22 04:10

Daniele Pistollato