Contents

今天写了一个C#的TreeView,需要带checkbox,msdn上TreeView.AfterCheck Event (System.Windows.Forms)之处理了子节点的递归选择问题,贴一下我写的父子节点递归选择。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
void tree_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action != TreeViewAction.Unknown)
{
UpdateCheckStatus(e);
}
}


// update check status for parent and child
private void UpdateCheckStatus(TreeViewEventArgs e)
{
CheckAllChildNodes(e.Node);
UpdateAllParentNodes(e.Node);
}


// updates all parent nodes recursively.

private void UpdateAllParentNodes(TreeNode treeNode)
{
TreeNode parent = treeNode.Parent;
if (parent != null)
{
if (parent.Checked && !treeNode.Checked)
{
parent.Checked = false;
UpdateAllParentNodes(parent);
}

else if (!parent.Checked && treeNode.Checked)
{
bool all = true;
foreach (TreeNode node in parent.Nodes)
{
if (!node.Checked)
{
all = false;
break;
}
}
if (all)
{
parent.Checked = true;
UpdateAllParentNodes(parent);
}
}
}
}


// updates all child tree nodes recursively.
private void CheckAllChildNodes(TreeNode treeNode)
{
foreach (TreeNode node in treeNode.Nodes)
{
node.Checked = treeNode.Checked;
if (node.Nodes.Count > 0)
{
// If the current node has child nodes, call the CheckAllChildsNodes method recursively.
this.CheckAllChildNodes(node);
}
}
}
Contents