带checkbox的C# TreeView处理父子节点选择
1 void tree_AfterCheck(object sender, TreeViewEventArgs e)
2 {3 if (e.Action != TreeViewAction.Unknown)
4 {5 UpdateCheckStatus(e);
6 }7 }
89 // update check status for parent and child
10 private void UpdateCheckStatus(TreeViewEventArgs e)11 {
12 CheckAllChildNodes(e.Node);13 UpdateAllParentNodes(e.Node);
14 }15
16 // updates all parent nodes recursively.17 private void UpdateAllParentNodes(TreeNode treeNode)
18 {19 TreeNode parent = treeNode.Parent;
20 if (parent != null)21 {
22 if (parent.Checked && !treeNode.Checked)23 {
24 parent.Checked = false;25 UpdateAllParentNodes(parent);
26 }27 else if (!parent.Checked && treeNode.Checked)
28 {29 bool all = true;
30 foreach (TreeNode node in parent.Nodes)31 {
32 if (!node.Checked)33 {
34 all = false;35 break;
36 }37 }
38 if (all)39 {
40 parent.Checked = true;41 UpdateAllParentNodes(parent);
42 }43 }
44 }45 }
4647 // updates all child tree nodes recursively.
48 private void CheckAllChildNodes(TreeNode treeNode)49 {
50 foreach (TreeNode node in treeNode.Nodes)51 {
52 node.Checked = treeNode.Checked;53 if (node.Nodes.Count > 0)
54 {55 // If the current node has child nodes, call the CheckAllChildsNodes method recursively.
56 this.CheckAllChildNodes(node);57 }
58 }59 }
![](http://img.zemanta.com/pixy.gif?x-id=205c14b1-4381-8566-8571-37bf53bec972)