winform TreeView 节点选择

winform TreeView 节点选择

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string tag = "True";
        StringBuilder nodesTag;
        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="treeNode"></param>
        /// <param name="nodeChecked"></param>
        private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                node.Checked = nodeChecked;
                node.Tag = tag;////记得在这里为选中的项目设置tag属性
                if (node.Nodes.Count > 0)
                {
                    this.CheckAllChildNodes(node, nodeChecked);
                }
            }
        }

        private void TraversNodes(TreeNode parent)
        {
            TreeNode node = parent;
            if (node != null)
            {
                if (node.Tag != null && node.Tag.ToString() == tag)
                    nodesTag.AppendFormat("node:{0} has checked\n", node.Text);

                if (node.FirstNode != null)////如果node节点还有子节点则进入遍历
                {
                    TraversNodes(node.FirstNode);
                }
                if (node.NextNode != null)////如果node节点后面有同级节点则进入遍历
                {
                    TraversNodes(node.NextNode);
                }
            }
        }
        /// <summary>
        /// 已选中或取消选中框发生事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
            {
                TreeNode node = e.Node;
                if (node.Tag == null)
                    node.Tag = tag;//附加结点信息
                else
                    node.Tag = null;

                CheckAllChildNodes(e.Node, e.Node.Checked);

                //选中父节点 
                bool bol = true;
                if (e.Node.Parent != null)
                {
                    for (int i = 0; i < e.Node.Parent.Nodes.Count; i++)
                    {
                        if (!e.Node.Parent.Nodes[i].Checked)
                            bol = false;
                    }
                    e.Node.Parent.Checked = bol;

                    ////记得如果父节点被选中或取消,记得设置它的tag
                    if (bol)
                    {
                        e.Node.Parent.Tag = tag;
                    }
                    else
                    {
                        e.Node.Parent.Tag = null;
                    }
                }
            }
        }
    }

 

winform TreeView 节点选择

上一篇:[转]Delphi Form的释放和隐藏:free,hide,close


下一篇:linux 编译win32程序