asp.net treeview 總結


 

網上關於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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM