Wednesday, 1 April 2015

Watch this example on YouTube:

Copy and paste the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class TreeViewTest3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TreeView myTree = new TreeView();
            myTree.ExpandDepth = 1;
            myTree.ID = "TEST";
            myTree.CollapseAll();
            myTree.ShowCheckBoxes = TreeNodeTypes.All;

            TreeNode tNode1 = new TreeNode();
            tNode1.Text = "HeadNode1";
            tNode1.Value = "HeadNode1";

            TreeNode h1ChildNode1 = new TreeNode();
            h1ChildNode1.Text = "Head1Child1";
            tNode1.ChildNodes.Add(h1ChildNode1);

            TreeNode h1GrandChild1 = new TreeNode();
            h1GrandChild1.Text = "Head1Child1Grand1";
            h1ChildNode1.ChildNodes.Add(h1GrandChild1);

            TreeNode h1ChildNode2 = new TreeNode();
            h1ChildNode2.Text = "Head1Child2";
            tNode1.ChildNodes.Add(h1ChildNode2);

            TreeNode h1ChildNode3 = new TreeNode();
            h1ChildNode3.Text = "Head1Child3";
            tNode1.ChildNodes.Add(h1ChildNode3);

            myTree.Nodes.Add(tNode1);

            CheckOrUncheck(myTree, true);
            form1.Controls.Add(myTree);
        }

        protected TreeView CheckOrUncheck(TreeView t, bool check){
            foreach(TreeNode tn in t.Nodes){
                tn.Checked = check;
                if (tn.ChildNodes.Count > 0)
                {
                    foreach (TreeNode ch1 in tn.ChildNodes)
                    {
                        ch1.Checked = check;
                    }
                }
            }

            return t;
        }
    }
}

No comments:

Post a Comment