hopeless

导航

关于TreeView控件父子节点Checked属性完美控制的实现类(C#) 的改进

主要功能:

当在TreeView控件中选中父节点时,子节点全部选中;并能根据各子节点的选中状态自动改变父节点的选中状态。

使用方法:

直接在TreeView控件的AfterCheck(object sender, TreeViewEventArgs e)事件中调用TreeViewCheck类的CheckControl(TreeViewEventArgs e)方法并传入参数e即可。

类代码:
程序代码 程序代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace TreeViewCheck
{
    /// <summary>
    /// 树节点上下文Checked属性控制
    /// </summary>
    public static class TreeViewCheck
    {
        /// <summary>
        /// 系列节点 Checked 属性控制
        /// </summary>
        /// <param name="e"></param>
        public static void CheckControl(TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
            {
                if (e.Node != null)
                {
                    CheckParentNode(e.Node, e.Node.Checked);
                }

                if (e.Node.Nodes.Count > 0)
                {
                    CheckAllChildNodes(e.Node, e.Node.Checked);
                }
            }
        }

        #region 私有方法

        //改变所有子节点的状态
        private static void CheckAllChildNodes(TreeNode pn, bool IsChecked)
        {
            foreach (TreeNode tn in pn.Nodes)
            {
                tn.Checked = IsChecked;

                if (tn.Nodes.Count > 0)
                {
                    CheckAllChildNodes(tn, IsChecked);
                }
            }
        }

        //改变父节点的选中状态
        private static void CheckParentNode(TreeNode curNode, bool IsChecked)
        {
            bool bChecked = true;

            if (curNode.Parent != null)
            {
                foreach (TreeNode node in curNode.Parent.Nodes)
                {
                    if (node.Checked == false)
                    {
                        bChecked = false;
                        break;
                    }
                }

                if (bChecked)
                {
                    curNode.Parent.Checked = true;
                    CheckParentNode(curNode.Parent, true);
                }
                else
                {
                    curNode.Parent.Checked = false;
                    CheckParentNode(curNode.Parent, false);
                }
            }
        }

        #endregion
    }
}


示例代码:
程序代码 程序代码
        //树节点上下文Checked属性控制
        private void tv_AfterCheck(object sender, TreeViewEventArgs e)
        {
            TreeViewCheck.CheckControl(e);
        }

posted on 2009-05-18 16:37  hopeless  阅读(690)  评论(1)    收藏  举报