Expanding a treeview from a path for any number of levels.

G

Guest

I have finally developed some code that allows you to re populate a tree view
and re select the last node that was clicked. However, you have to hard code
it for the number of levels the tree view could possibly be expanded to. Any
ideas?

//The test program has a button to set the path and a button to execute the
path finding code.

//This is so that you can close the treeview back up to the root to ensure
the correct code is selected

string delimit = @"\";
char [] delimiter = delimit.ToCharArray();
string [] split = null;

split = path.Split( delimiter );

int CountUnderRoot = treeView1.Nodes[0].Nodes.Count ;
if( split.Length > 1 )
{
for( int i =0; i<CountUnderRoot; i++)
{
if(treeView1.Nodes[0].Nodes.Text == split[1].ToString())
{
Debug.WriteLine("yes");
int countUnderLevel1 = treeView1.Nodes[0].Nodes.Nodes.Count;
if( countUnderLevel1 > 0 && split.Length == 3 )
{
for( int j =0; j<countUnderLevel1; j++)
{
if(treeView1.Nodes[0].Nodes.Nodes[j].Text == split[2].ToString())
{
treeView1.Focus();
treeView1.SelectedNode = treeView1.Nodes[0].Nodes.Nodes[j];
break;
}
}
}

else
{
treeView1.Focus();
treeView1.SelectedNode = treeView1.Nodes[0].Nodes;
break;
}
}
}
}

else
{
treeView1.Focus();
treeView1.SelectedNode = treeView1.Nodes[0];
}
 
G

Guest

After all that wonderful code, after a moment of inspiration(and guess work).
When i click the node i want i store the selected node in a private treeNode
variable.

I then close the tree View and say,

treeView1.SelectedNode = the priavte tree node variable.

The node seems to be selected correctly. I will now move it from my demo app
into the real thing. Fingers crossed.
 
M

Marc Gravell

How about something like:

private static void SelectNode(TreeView treeView, string indexPath) {
TreeNode node = null;
TreeNodeCollection nodes = treeView.Nodes;
foreach (string item in indexPath.Split('/')) {
node = nodes[int.Parse(item)];
nodes = node.Nodes;
}
if (node != null) {
treeView.SelectedNode = node;
node.EnsureVisible();
}
}
private static string GetIndexPath(TreeNode node) {
StringBuilder sb = new StringBuilder();
bool first = true;
while (node != null) {
if (first)
first = false;
else
sb.Append('/');
sb.Append(node.Index);
node = node.Parent;
}
return sb.ToString();
}
private void button1_Click(object sender, EventArgs e) {
SelectNode(treeView1, "0/1/0");
}

private void button2_Click(object sender, EventArgs e) {
MessageBox.Show(GetIndexPath(treeView1.SelectedNode));
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top