一佳一

记录像1+1一样简洁的代码

导航

asp.net treeview 总结

Posted on 2013-12-30 11:58  一佳一  阅读(11292)  评论(1编辑  收藏  举报

 

网上关于Treeview的代码虽然多 但是都是很乱 实用性和正确性也不是很好 只好自己写一套了,时间比较紧张 性能可能还需调整

以用户组织的一个实际例子来讲诉Treeview的用法吧

组织表结构:

用户组织表结构:

前台界面aspx

<form id="Form1" runat="server">
        <table>

            <tr>
                <td class="contentTD">
                    <div id="MyTreeDiv">
                        <asp:TreeView ShowCheckBoxes="All" ID="MyTreeView" ImageSet="Contacts" runat="server" ExpandDepth="0" Width="400px" BorderStyle="Solid" BorderWidth="1px">
                        </asp:TreeView>
                    </div>
                </td>
            </tr>
            <tr>

                <td class="content">
                    <asp:Button ID="btnSubmit" runat="server" Text="提 交" CssClass="dotNetButton" OnClick="btnSubmit_Click" /><input type="button" class="glbutton" onclick="history.go(-1);"
                        value="返 回" />
                    <asp:ListBox ID="ListBox1" Visible="false" runat="server"></asp:ListBox>
                </td>
            </tr>
        </table>
    </form>

 

 

js控制父节点选中子节点自动选中

<script>
        function Davidovitz_HandleCheckbox() {
            var element = event.srcElement;
            if (element.tagName == "INPUT" && element.type == "checkbox") {
                var checkedState = element.checked;
                while (element.tagName != "TABLE") // Get wrapping table
                {
                    element = element.parentElement;
                }

                Davidovitz_UnCheckParents(element); // Uncheck all parents

                element = element.nextSibling;

                if (element == null) // If no childrens than exit
                    return;

                var childTables = element.getElementsByTagName("TABLE");
                for (var tableIndex = 0; tableIndex < childTables.length; tableIndex++) {
                    Davidovitz_CheckTable(childTables[tableIndex], checkedState);
                }
            }
        }

        // Uncheck the parents of the given table, Can remove the recurse (redundant)
        function Davidovitz_UnCheckParents(table) {
            if (table == null || table.rows[0].cells.length == 2) // This is the root
            {
                return;
            }
            var parentTable = table.parentElement.previousSibling;
            Davidovitz_CheckTable(parentTable, false);
            Davidovitz_UnCheckParents(parentTable);
        }

        // Handle the set of checkbox checked state
        function Davidovitz_CheckTable(table, checked) {
            var checkboxIndex = table.rows[0].cells.length - 1;
            var cell = table.rows[0].cells[checkboxIndex];
            var checkboxes = cell.getElementsByTagName("INPUT");
            if (checkboxes.length == 1) {
                checkboxes[0].checked = checked;
            }
        }

    </script>

 

后台代码.cs

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.MyTreeView.Attributes.Add("onclick", "Davidovitz_HandleCheckbox()");

                bind();
            }
        }
        //数据绑定
        private void bind()
        {
            this.MyTreeView.Nodes.Clear();
            //读取组织列表
            DataTable dt = new T_GroupManager().GetDataTableBySQL(" and FState=1 and FCreatorID = " + Request.QueryString["id"]);

            this.ViewState["ds"] = dt;
            //调用递归函数,完成树形结构的生成   
            AddTree(0, (TreeNode)null);

            if (Request.QueryString["id"] != null)
            {
                //根据用户ID查找对应的用户组织结构,勾上
                List<T_UserGroup> list = new T_UserGroupManager().GetAllBySQL(" and FUSerID=" + Request.QueryString["id"]).ToList();
                ViewState["UserGroup"] = list;
                foreach (T_UserGroup item in list)
                {
                    for (int i = 0; i < this.MyTreeView.Nodes.Count; i++)
                    {
                        if (MyTreeView.Nodes[i].ChildNodes.Count > 0)  //判断是否还有子节点
                        {
                            SetNode(MyTreeView.Nodes[i]);
                        }
                        if (MyTreeView.Nodes[i].Value == item.FGroupID.ToString())       //判断是否被选中
                        {
                            MyTreeView.Nodes[i].Checked = true;
                        }
                    }
                }
            }
        }
        //查找子节点
        public void SetNode(TreeNode node)
        {
            if (Request.QueryString["id"] != null)
            {
                //根据ID查找对应的组织结构,勾上
                List<T_UserGroup> list = ViewState["UserGroup"] as List<T_UserGroup>;
                foreach (T_UserGroup item in list)
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].ChildNodes.Count > 0)  //判断是否还有子节点
                        {
                            SetNode(node.ChildNodes[i]);  //递归查找
                        }
                        if (node.ChildNodes[i].Value == item.FGroupID.ToString())       //判断是否被选中
                        {
                            node.ChildNodes[i].Checked = true;
                        }
                    }
                }
            }
        }

        //递归添加树的节点
        public void AddTree(int ParentID, TreeNode pNode)
        {
            DataTable ds = (DataTable)this.ViewState["ds"];
            DataView dvTree = new DataView(ds);
            //过滤ParentID,得到当前的所有子节点
            dvTree.RowFilter = "[FParentUserID] = " + ParentID;

            foreach (DataRowView Row in dvTree)
            {
                TreeNode Node = new TreeNode();
                if (pNode == null)
                {
                    //添加根节点
                    Node.Text = Row["FGroupName"].ToString();
                    Node.Value = Row["PID"].ToString();
                    this.MyTreeView.Nodes.Add(Node);
                    Node.Expanded = true;
                    //再次递归
                    AddTree(Int32.Parse(Row["PID"].ToString()), Node);
                }
                else
                {
                    //添加当前节点的子节点
                    Node.Text = Row["FGroupName"].ToString();
                    Node.Value = Row["PID"].ToString();
                    pNode.ChildNodes.Add(Node);
                    Node.Expanded = true;
                    //再次递归
                    AddTree(Int32.Parse(Row["PID"].ToString()), Node);
                }
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < MyTreeView.Nodes.Count; i++)
            {
                if (MyTreeView.Nodes[i].ChildNodes.Count > 0)  //判断是否还有子节点
                {
                    GetNode(MyTreeView.Nodes[i]);
                }
                if (MyTreeView.Nodes[i].Checked == true)       //判断是否被选中
                {
                    string s = MyTreeView.Nodes[i].Value.ToString();
                    ListBox1.Items.Add(s);
                }
            }
            T_UserGroupManager gm = new T_UserGroupManager();
            //清空
            List<T_UserGroup> list = ViewState["UserGroup"] as List<T_UserGroup>;
            foreach (T_UserGroup item in list)
            {
                gm.DeleteByPID(item.PID);
            }
            int id = Convert.ToInt32(Request.QueryString["id"]);
            //保存
            foreach (var item in ListBox1.Items)
            {
                T_UserGroup ug = new T_UserGroup();
                ug.FUSerID = id;
                ug.FGroupID = Convert.ToInt32((item as ListItem).Value);
                ug.FState = 1;
                gm.Add(ug);
            }
            ShowJS("<script>alert('保存成功!');location = 'UserGroupInfo.aspx'</script>");
        }
        //获取选中节点
        public void GetNode(TreeNode node)
        {
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                if (node.ChildNodes[i].ChildNodes.Count > 0)  //判断是否还有子节点
                {
                    GetNode(node.ChildNodes[i]);               //递归查找
                }
                if (node.ChildNodes[i].Checked == true)     //判断是否被选中
                {
                    string s = node.ChildNodes[i].Value.ToString();
                    ListBox1.Items.Add(s);
                }
            }
        }
    }


基本上面就是全部代码了,实现了Treeview的读取和根据勾选保存,根据用户配置设置Treeview的勾选项

 

用了好一段时间才整理出来的,要转载的童鞋记得保留我的链接哦http://www.cnblogs.com/linyijia/p/3497503.html