Initially a TreeNode is created and child nodes are added under the node.
TreeNode tree = new TreeNode();
tree.Value = "Social Media";
tree.ImageUrl = "/images/home.png";
tree.ChildNodes.Add(new TreeNode("Facebook", "Facebook","/images/fb.png"));
tree.ChildNodes.Add(new TreeNode("G+","GPlus","/images/google.png"));
tree.ChildNodes.Add(new TreeNode("Printrest", "Printrest", "/images/pintrest.png"));
tree.ChildNodes.Add(new TreeNode("Twitter", "Twitter", "/images/twitter.jpg"));
Now lets add some child nodes under the created nodes. In this example the below would be the leaf nodes.
foreach (TreeNode node in tree.ChildNodes)
{
node.ChildNodes.Add(new TreeNode("Sri Lanka", string.Concat(node.Value,"-","SL"), "/images/countries/SL-flag.jpg"));
node.ChildNodes.Add(new TreeNode("Malaysia", string.Concat(node.Value,"-","ML"), "/images/countries/malaysia-flag.png"));
node.ChildNodes.Add(new TreeNode("USA", string.Concat(node.Value,"-","USA"), "/images/countries/US-Flag.png"));
node.ChildNodes.Add(new TreeNode("Britain", string.Concat(node.Value,"-","BRIT"), "/images/countries/Britain-flag.png"));
node.ChildNodes.Add(new TreeNode("Australia", string.Concat(node.Value,"-","AUS"), "/images/countries/Australia-Flag.png"));
node.ChildNodes.Add(new TreeNode("Netherlands", string.Concat(node.Value,"-","NL"), "/images/countries/netherlands-flag.png"));
node.ChildNodes.Add(new TreeNode("Egypt", string.Concat(node.Value,"-","EG"), "/images/countries/Egypt-Flag.png"));
node.ChildNodes.Add(new TreeNode("Greece", string.Concat(node.Value,"-","GR"), "/images/countries/greece_flag.png"));
node.ChildNodes.Add(new TreeNode("Germany", string.Concat(node.Value,"-","GE"), "/images/countries/germany-flag.png"));
node.ChildNodes.Add(new TreeNode("Canada", string.Concat(node.Value,"-","CA"), "/images/countries/canada_flag.png"));
node.ChildNodes.Add(new TreeNode("Brazil", string.Concat(node.Value,"-","BR"), "/images/countries/brazil-flag.png"));
}
The TreeNode is then set to a TreeView to be displayed in the Form.
TreeView view = new TreeView();
view.ShowCheckBoxes = TreeNodeTypes.All;
view.Nodes.Add(tree);
view.TreeNodeCheckChanged += view_TreeNodeCheckChanged;
view.Attributes.Add("onclick", "postBackByObject()");
form1.Controls.Add(view);
void view_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
if (e.Node.Checked)
{
CheckChildNodes(e.Node.ChildNodes);
}
else if (e.Node.Checked == false)
{
UncheckChildNodes(e.Node.ChildNodes);
}
}
private void UncheckChildNodes(TreeNodeCollection children)
{
foreach (TreeNode child in children)
{
if (child.Checked)
child.Checked = false;
UncheckChildNodes(child.ChildNodes);
}
}
private void CheckChildNodes(TreeNodeCollection children)
{
foreach (TreeNode child in children)
{
if (child.Checked == false)
child.Checked = true;
CheckChildNodes(child.ChildNodes);
}
}