Reputation: 447
I am using a TreeView
control to list all my menus so that I can give access to each user. How I will forced the parent node
to check = true
when one or more childnode
is checked by user?
I am using below code to check/uncheck all child nodes
when parent node
is checked.
private void treeView_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action != TreeViewAction.Unknown)
{
if (e.Node.Nodes.Count > 0)
{
CheckAllChildNodes(e.Node, e.Node.Checked);
}
}
}
private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
{
foreach (TreeNode node in treeNode.Nodes)
{
node.Checked = nodeChecked;
if (node.Nodes.Count > 0)
{
this.CheckAllChildNodes(node, nodeChecked);
}
}
}
Upvotes: 1
Views: 1748
Reputation: 1002
A TreeNode has a "Parent" property that should make it easy.
Untested code but should give you an idea.
private void CheckAllParentNodes(TreeNode treeNode, bool nodeChecked)
{
TreeNode parentNode = treeNode.Parent;
while (parentNode != null)
{
// check if parent has still checked child nodes
if (parent.Nodes.Any(n => n.Checked)) return;
parentNode.Checked = nodeChecked;
parentNode = parentNode.Parent;
}
}
Upvotes: 1