EFileTahi-A said:
For starters, I can't even retrieve the current selected node by using "this.myTreeView.SelectedNode" property.
It keeps saying me that the "object was not set in an property index" or something like that.
The SelectedNode property is a reference to the currently selected node, so if no node is selected, it's a null reference. So...
The most likely cause of this is that either your treeview has no nodes or there is no node selected from the treeview's nodes. Either way, it's a good idea to check the SelectedNode property to see if it's null (not currently holding a reference to a node) before using it, for ex:
Code:
private void button1_Click(object sender, System.EventArgs e)
{
TreeNode oNode = this.treeView1.SelectedNode;
if (oNode != null)
{
SelectNodeAndParents(oNode);
}
else
{
MessageBox.Show("You must select a node first");
}
}
EFileTahi-A said:
So, How can I say to the treeview to select all the parent nodes from the current selected one?
Each node has a Parent property that contains a reference to its parent node - or null if the node has no parent (ie, it's a top level node).
To select a node and all of its parents you'd need to select the node, see if it had a parent and select it, see if the parent had a parent and select, and so on. This is something you can so in a loop (somewhat recursively). For example:
Code:
private void SelectNodeAndParents(TreeNode oNode)
{
oNode.Checked = true;
//oNode.Checked = !oNode.Checked; // Use this if you want to toggle.
TreeNode oParent = oNode.Parent;
while (oParent != null)
{
oParent.Checked = true;
//oParent.Checked = !oParent.Checked; // Use this if you want to toggle.
oParent = oParent.Parent;
}
}
In the routine above a node is passed in, the node itself is checked, and then a loop executes that keeps selecting parent nodes as long as they exist (oParent is initially set to the parent of the node that's passed in, then it's set to the next parent in line as long as the loop continues - the loop keeps going until it encounters a parent that's null, which indicates a top level node and end of the line).
I've attached the source (only) of a scrappy sample project that uses the code above on some sample nodes if you'd care to see this working...
Good luck,
Paul