المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Progmatically Creating TreeNodes and Child Nodes [modified]



C# Programming
03-27-2009, 08:40 PM
Hi guys

I’m at my wits end with TreeNodes. http://www.barakasoft.com/script/Forums/Images/smiley_dead.gif

What i'm trying to do, to me is very simple. But for some reason I just can't get my head around it! http://www.barakasoft.com/script/Forums/Images/smiley_sigh.gif

I’m currently working on a project where basically I’m splitting a Url address into a string array and creating each node and child node from the url segments (just like the Windows Explorer.)

\\ this is the plan

1) step through each url
string url1 = @"www.somedomain.com\home\about_us.aspx";
string url2 = @"www.somedomain.com\home\contact_us.aspx";
string url3 = @"www.somedomain.com\home\main.aspx";

2) split the current url into sections

3) process the url sections and create new nodes and child nodes or merge nodes if needed

4) output results


the final output I'm trying to get...

+ www.somedomain.com
_+ home
___+ about_us.aspx
___+ contact_us.aspx
___+ main.aspx


but in short i'm getting something like...

+ www.somedomain.com
_+ home
___+ about_us.aspx
___+ contact_us.aspx
___+ main.aspx
_+ home
___+ about_us.aspx
___+ contact_us.aspx
___+ main.aspx


Looking at the code below, Is there another way around this problem or am I just being stupid???


Any help would be very much appreciated. Please feel free to rip the hell out of my coding as I've kind of lost the plot!

Thanks again! http://www.barakasoft.com/script/Forums/Images/smiley_smile.gif


private void Form1_Load(object sender, EventArgs e)
{
TreeNode treeNode = new TreeNode();
treeView1.Nodes.Add(treeNode);
treeView1.PathSeparator = "\\"

// Add first url address
BuildNodes(treeNode,@"1\2\3\4\5\6\7");

// Add the next url address merging duplicate folders together...
BuildNodes(treeNode, @"1\2\4\5\6");
}

private void BuildNodes(TreeNode treeNode, string address)
{
string[] add = SplitNodes(address);

int max = add.Length;
string key = String.Empty;

TreeNode[] treeNodes = new TreeNode[max];
key = add[0];

treeNodes[0] = treeNode;
treeNodes[0].Text = add[0];
treeNodes[0].Name = key;

for (int i = 1; i < max; i++)
{
key = GetKey(key, add[i]);

treeNodes[i] = new TreeNode();
treeNodes[i].Text = add[i];
treeNodes[i].Name = key;

TreeNode[] tns = treeNodes[i - 1].Nodes.Find(treeNodes[i].Name, true);

// if node exists skip it else add the new node
if (tns.Length == 0)//if
{
treeNodes[i - 1].Nodes.Add(treeNodes[i]);
}
}

}

private string GetKey(string key, string value)
{
string delimiter = treeView1.PathSeparator;

if (key == String.Empty)
return value;
else
return String.Format(@"{0}{1}{2}", key, delimiter, value);
}

private string[] SplitNodes(string nodeString)
{
char[] delimiter = treeView1.PathSeparator.ToCharArray();
return nodeString.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
}


modified on Friday, March 27, 2009 12:01 PM