Winfrom TreeView 绑定数据

在Winform。。TreeView绑定数据
RoleManager tManager = new RoleManager();
            DataTable dt = tManager.FindRoleRigthByRoleid(listRoleView.SelectedItems[0].Text);
            TreeViewBinding(dt, liv_alreadyRole);

绑定数据方法:

 
 private void TreeViewBinding(DataTable dt, TreeView tv)
        {
            tv.Nodes.Clear();
            foreach (DataRow item_p in dt.Rows)
            {
                if (item_p["ParentNode"].ToString() == "00")
                {
                    TreeNode nodep = new TreeNode(item_p["NodeName"].ToString());
                    nodep.Tag = item_p;
                    tv.Nodes.Add(nodep);
                    foreach (DataRow item_child in dt.Rows)
                    {
                        if (item_child["ParentNode1"].ToString() == item_p["Nodeid"].ToString())
                        {
                            TreeNode cnode = new TreeNode(item_child["NodeName"].ToString());
                            cnode.Tag = item_child;
                            nodep.Nodes.Add(cnode);
                        }
                    }
                }
            }
        }
 

父节点:选中的时候 选中当前所有的子节点:

设置当前TreeViw AfterCheck的事件:

 //event
   void ListFullRoleAfterCheck(object sender, TreeViewEventArgs e)
        {
           
                if (e.Action == TreeViewAction.ByMouse)
                {
                    if (e.Node.Checked)
                    {
                        //取消节点选中状态之后,取消所有父节点的选中状态
                        SetChildNode(e.Node, true);
                        if (e.Node.Parent != null)
                        {
                            SetParentNode(e.Node, true);
                        }
                    }
                    else
                    {
                        //取消节点选中状态之后,取消所有父节点的选中状态
                        SetChildNode(e.Node, false);
                        //如果节点存在父节点,取消父节点的选中状态
                        if (e.Node.Parent != null)
                        {
                            SetParentNode(e.Node, false);
                        }
                    }
                }
      
        }

 

 
   private void SetParentNode(TreeNode node, bool state)
        {
            TreeNode nodes = node.Parent;
            nodes.Checked = state;
            if (node.Parent.Parent != null)
            {
                SetParentNode(node, state);
            }
        }
    private void SetChildNode(TreeNode node, bool state)
        {
            TreeNodeCollection nodes = node.Nodes;
            if (nodes.Count > 0)
            {
                foreach (TreeNode cloneable in nodes)
                {
                    cloneable.Checked = state;
                    SetChildNode(cloneable, state);
                }
            }
        }

 

 

 
posted @ 2012-11-15 17:22  在 水 一 方  阅读(2070)  评论(0编辑  收藏  举报