TreeView节点选中问题

实现选中树父节点,子节点选中,子节点全部选中时,父节点选中

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;

namespace 弹出组织架构
{
    public partial class Index : System.Web.UI.Page
    {
        private readonly string stringConnectString = "Data Source=.;Initial Catalog=test;Persist Security Info=false;User Id=sa;Password=sa";
        private const string sql = "select * from course";
        protected void Page_Load(object sender, EventArgs e)
        {
            //TreeView1.Attributes.Add("onclick", "OnTreeNodeChecked('"+ TreeView1.ID+ "'," + TreeView1.ClientID + ")");
            TreeView1.Attributes.Add("onclick", "checkone()");
            bindData();
        }
        protected void Confirm_Click(object sender, EventArgs e)
        {
            Response.Write("hello");
        }
        /// <summary>
        /// 绑定树
        /// </summary>
        protected void bindData()
        {
            TreeNode treeNode = new TreeNode();
            treeNode.Text = "项目简介";
            treeNode.Value = "1";
            TreeView1.Nodes.Add(treeNode);
            SqlConnection conn = new SqlConnection(stringConnectString);
            DataTable dt = new DataTable();
            DataSet ds=new DataSet();
            try
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                da.Fill(ds);
            }
            catch (Exception err)
            {

                throw new Exception("错误信息为:" + err.Message + err.StackTrace);
            }
            finally
            {
                conn.Dispose();
            }
            dt = ds.Tables[0];
            //首先绑定一级
            DataRow[] rows = dt.Select("NodeParentId=-1");
            if (rows.Length>0)
            {
                foreach (DataRow item in rows)
                {
                    TreeNode node = new TreeNode();
                    node.Value = item["nodeId"].ToString();
                    node.Text = item["nodeName"].ToString();
                    TreeView1.Nodes.Add(node);
                    GetTree(node.Value, dt, node);
                }
            }
        }
        /// <summary>
        /// 递归生成树
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="dt"></param>
        /// <param name="fatherNode"></param>
        protected void GetTree(string parentId, DataTable dt, TreeNode fatherNode)
        {
            //递归绑定
            DataRow[] rows = dt.Select("NodeParentId=" + parentId);
            if (rows.Length>0)
            {
                foreach (DataRow item in rows)
                {
                    TreeNode node = new TreeNode();
                    node.Value = item["nodeId"].ToString();
                    node.Text = item["nodeName"].ToString();
                    fatherNode.ChildNodes.Add(node);
                    GetTree(node.Value, dt, node);
                }
            }
        }
    }
}

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="弹出组织架构.Index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #btnConfirm
        {
            width: 90px;
            height: 26px;
        }
    </style>
    <%--<script language='javascript' type='text/javascript'>
        var ClienName;
        var tree; //取出TreeView在客户端的表示对象
        ///////////////////TreeView在后台的控件ID,Obj表示TreeView
        function OnTreeNodeChecked(controlID, obj) {
            //debugger
            tree = obj; //取出TreeView在客户端的表示对象
            ClienName = tree.id.substring(0, tree.id.indexOf(controlID)); //取出TreeView在客户ID的前缀
            var ele = event.srcElement;
            if (ele.type == 'checkbox') {
                //当前节点全选 
                // var subLength=ClienName.length+14;//取出当前复选框的索引值
                var subLength = tree.id.length + 1;
                var nowIndex = ele.id.substring(subLength).substring(0, ele.id.substring(subLength).indexOf("C"));

                var childrenDivID = ele.id.replace('CheckBox', 'Nodes');
                var div = document.getElementById(childrenDivID); //获取同级的Div
                if (div != null) //判断同级的Div是否为Null
                {
                    var checkBoxs = div.getElementsByTagName('INPUT');
                    for (var i = 0; i < checkBoxs.length; i++) {
                        if (checkBoxs[i].type == 'checkbox')
                            checkBoxs[i].checked = ele.checked;
                    }
                }
                //处理选择当前节点的父节点的选中和取消选中
                ChkParent(nowIndex, ele.id, ele.checked);
            }
        }

        function ChkParent(index, childId, flag) {
            //寻找当前节点的父节点(即寻找上级的DIV)
            for (i = index; i >= 0; i--) {
                var id = tree.id + "n" + i + "CheckBox"; //当前CheckBox的ID
                var parent = document.getElementById(id); //获取当前的CheckBox
                if (parent != null)//判断获取的当前的CheckBox是否为空
                {
                    var childrenDivID = parent.id.replace('CheckBox', 'Nodes');
                    var div = document.getElementById(childrenDivID); //获取同级的Div
                    if (div == null) //判断同级的Div是否为Null
                    {
                        continue;
                    }
                    else {
                        chk(div, flag);
                        break;
                    }
                }
            }
        }
        //根据找到的div逐级处理各级CheckBox的状态
        function chk(obj, flag) {
            var chkID = obj.id.replace('Nodes', 'CheckBox');
            var chkbox = document.getElementById(chkID); //获取同级的CheckBox
            if (chkbox != null) {
                //选中状态
                if (flag) {
                    chkbox.checked = flag;
                    //如果为顶层则终止递归
                    if (chkID == tree.id + "n0CheckBox") {
                        return;
                    }
                    //递归处理各级CheckBox的状态
                    chk(obj.parentNode, flag)
                }
                ///非选中状态
                else {
                    //如果为顶层则终止递归
                    if (chkID == tree.id + "n0CheckBox") {
                        return;
                    }
                    //判断当前节点下面是否有Checkbox选中,如果有选中的,当前节点的CheckBox不取消选中状态,否则取消
                    var checkBoxs = obj.getElementsByTagName('INPUT');
                    var sel = false; //记录当前节点下面是否有Checkbox选中
                    for (var i = 0; i < checkBoxs.length; i++) {
                        if (checkBoxs[i].type == 'checkbox') {
                            if (checkBoxs[i].checked) {
                                sel = true;
                                break;
                            }
                        }
                    }
                    if (!sel) {
                        chkbox.checked = flag;
                    }
                    chk(obj.parentNode, flag)
                }
            }
            else {
                return;
            }
        }
    </script>--%>
    <script language="javascript" type="text/javascript">
        function getcheck() {
            var o = window.event.srcElement;
            if (o.tagName == "INPUT" && o.type == "checkbox") //点击treeview的checkbox是触发
            {
                var d = o.id; //获得当前checkbox的id;

                var e = d.replace("CheckBox", "Nodes"); //通过查看脚本信息,获得包含所有子节点div的id
                var div = window.document.getElementById(e); //获得div对象
                if (div != null) //如果不为空则表示,存在子节点
                {
                    var check = div.getElementsByTagName("INPUT"); //获得div中所有的已input开始的标记
                    for (i = 0; i < check.length; i++) {
                        if (check[i].type == "checkbox") //如果是checkbox
                        {
                            check[i].checked = o.checked; //字节点的状态和父节点的状态相同,即达到全选
                        }

                    }

                }
                //else //点子节点的时候,使父节点的状态改变,即不为全选
                //{
                //处理父节点
                var divid = o.parentElement.parentElement.parentElement.parentElement.parentElement; //子节点所在的div

                while (divid != null) {

                    var id = divid.id.replace("Nodes", "CheckBox"); //获得根节点的id
                    var checkbox = divid.getElementsByTagName("INPUT"); //获取所有子节点数
                    var s = 0;
                    for (i = 0; i < checkbox.length; i++) {
                        if (checkbox[i].checked) //判断有多少子节点被选中
                        {
                            s++;
                        }
                    }

                    if (s == checkbox.length) //如果全部选中 或者 选择的是另外一个根节点的子节点 ,
                    {                               //    则开始的根节点的状态仍然为选中状态
                        window.document.getElementById(id).checked = true;
                    }
                    else {                               //否则为没选中状态
                        window.document.getElementById(id).checked = false;
                    }
                    divid = window.document.getElementById(id).parentElement.parentElement.parentElement.parentElement.parentElement;

                }

            }

        }


        //每个节点只能选一个且不能影响其他项
        function checkone() {
            var o = event.srcElement;
            if (o.tagName == "INPUT" && o.type == "checkbox") //点击treeview的checkbox是触发
            {
                var divid = o.parentElement.parentElement.parentElement.parentElement.parentElement; //子节点所在的div

                var checkbox = divid.getElementsByTagName("INPUT"); //获取所有子节点数


                for (var i = 0; i < checkbox.length; i++) {

                    if (checkbox[i].type == "checkbox" && checkbox[i] != o) //如果是checkbox
                    {

                        checkbox[i].checked = false;

                    }

                }

            }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="All">
        </asp:TreeView>
        &nbsp;<input id="btnConfirm" type="button" value="确定" runat="server" onserverclick="Confirm_Click" /></div>
    </form>
</body>
</html>

 后台获取选中的值:

       protected void Confirm_Click(object sender, EventArgs e)
        {
            IList<string> list = new List<string>();//定义一个泛型集合     
            TreeNodeCollection nodeList = TreeView1.CheckedNodes;//得到所有选中复选框的节点集合 
            foreach (TreeNode node in nodeList)//遍历集合,获得被选中节点的值    
            { list.Add(node.Value); }
        }

你可能感兴趣的:(treeview)