在Winform中的TreeView控件,实现选中/取消选中父节点则自动选择/取消选中对应子节点
时间:2011-04-07 来源:V587
用两个递归来设置子节点和父节点的状态,如下
private void CheckChild(TreeNode node)
{
if (node.Nodes.Count != 0)
{
foreach (TreeNode item in node.Nodes)
{
item.Checked = node.Checked;
CheckChild(item);
}
}
}
private void CheckParent(TreeNode node)
{
if (node.Parent != null)
{
int count = 0;
foreach (TreeNode item in node.Parent.Nodes)
{
if (item.Checked)
{
count++;
}
}
node.Parent.Checked = (count == node.Parent.Nodes.Count);
CheckParent(node.Parent);
}
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
CheckChild(e.Node);
CheckParent(e.Node);
}