During development, the Treeview control is often used to display the organizational structure, directory structure, and attribute checkedboxs.
The following is an example of selecting and canceling a node. If a node has a subnode, you can select all the subnodes. If you cancel the selected status of a node, if both the current node and the parent node exist, the selection of the parent node will be canceled.
:
CodeAs follows:
Code
Using System;
Using System. Collections. Generic;
Using System. componentmodel;
Using System. Data;
Using System. drawing;
Using System. text;
Using System. Windows. forms;
namespace windowsapplication6
{< br> Public partial class treeviewtest: form
{< br> Public treeviewtest ()
{< br> initializecomponent ();
}
private void treeviewtest_load ( Object sender, eventargs e)
{< br> treeview1.expandall ();
}
Private VoidTreeviewappsaftercheck (ObjectSender, treevieweventargs E)
{
If (E. Action = Treeviewaction. bymouse)
{
Textbox1.text = E. node. text;
If (E. node. Checked)
{
// Cancels the selected status of all parent nodes.
Setchildnodecheckedstate (E. node, True );
}
Else
{
// Cancels the selected status of all parent nodes.
Setchildnodecheckedstate (E. node, False );
// If a parent node exists, deselect the selected status of the parent node.
If (E. node. Parent ! = Null )
{
Setparentnodecheckedstate (E. node, False );
}
}
}
}
// Cancels the selected status of all parent nodes.
Private Void Setparentnodecheckedstate (treenode currnode, Bool State)
{
Treenode parentnode = Currnode. parent;
Parentnode. Checked = State;
If (Currnode. Parent. Parent ! = Null )
{
Setparentnodecheckedstate (currnode. Parent, State );
}
}
// After a node is selected, all the child nodes of the node are selected.
Private Void Setchildnodecheckedstate (treenode currnode, Bool State)
{
Treenodecollection nodes = Currnode. nodes;
If (Nodes. Count > 0 )
Foreach (Treenode TN In Nodes)
{
Tn. Checked = State;
Setchildnodecheckedstate (TN, State );
}
}
}
}