Code
1 using System;
2 using System. Collections. Generic;
3 using System. ComponentModel;
4 using System. Data;
5 using System. Drawing;
6 using System. Linq;
7 using System. Text;
8 using System. Windows. Forms;
9
10 namespace MyNetShop
11 {
12 public partial class Form1: Form
13 {
14 public Form1 ()
15 {
16 InitializeComponent ();
17}
18
19/** event: Added By Wangxu */
20 private void treeView1_MouseClick (object sender, MouseEventArgs e)
21 {
22 // obtain the clicked Node
23 TreeNode root = treeView1.GetNodeAt (new Point (e. X, e. Y ));
24 // whether the node is selected
25 bool isChecked = root. Checked;
26
27 if (root! = Null)
28 {
29 // The selected status of the node affects the status of its child node
30 FooChild (root, isChecked );
31 // The selected status of the node affects the status of its parent node
32 FooParent (root );
33}
34}
35
36/*** method: recursive subnode Selects all or does not select Modify By Wangxu 2010-2-25 */
37 private void FooChild (TreeNode node, bool isChecked)
38 {
39 node. Checked = isChecked;
40 foreach (TreeNode nd in node. Nodes)
41 FooChild (nd, isChecked );
42}
43
44/** method: recursive parent node Selects all or does not select Add By Wangxu 2010-2-25 */
45 private void FooParent (TreeNode root)
46 {
47 if (root. Parent! = Null)
48 {
49 // Number of sibling nodes selected
50 int brotherNodeCheckedCount = 0;
51 // traverse the sibling node of the node
52 foreach (TreeNode node in root. Parent. Nodes)
53 {
54 if (node. Checked = true)
55 brotherNodeCheckedCount + = 1;
56}
57 // No sibling Node Selected
58 if (brotherNodeCheckedCount = 0)
59 {
60 TreeNode parentNode = root. Parent;
61 parentNode. Checked = false; // The parent node is not selected either.
62 FooParent (parentNode );
63}
64 // if one of the sibling nodes is selected
65 if (brotherNodeCheckedCount = 1)
66 {
67 TreeNode parentNode = root. Parent;
68 parentNode. Checked = true;
69 FooParent (parentNode); // its parent node is also selected
70}
71}
72}
73}
74}
75