I have a TreeView populated from database with lots of node, and each node may have some children and there is no fixed role like 2 depthes, it may be very deep.

Imagine that the TreeView CheckBoxes are RadioButtons, I want my TreeView just to have one checked node at a time. I have tried AfterCheck and BeforeCheck events but they fall into forever loop, what can I do?

I want to keep my checked node CHECKED and uncheck all other nodes but I can't. Waiting for your smart points. Thanks.

Here's the code I have tried but ended up with a StackOverFlow exception, and I thought maybe it's saying go and check it on StackOverflow :D

private void tvDepartments_AfterCheck(object sender, TreeViewEventArgs) 
{
   List<TreeNode> nodes = new List<TreeNode>();
   if (rdSubDepartments.Checked)
       CheckSubNodes(e.Node, e.Node.Checked);
   else if (rdSingleDepartment.Checked)
   {
       foreach (TreeNode node in tvDepartments.Nodes)
       {
           if (node != e.Node)
               node.Checked = false;
       }
   }
}


public void CheckSubNodes(TreeNode root, bool checkState)
{
    foreach (TreeNode node in root.Nodes)
    {
        node.Checked = checkState;
        if (node.Nodes.Count > 0)
            CheckSubNodes(node, checkState);
    }
}
有帮助吗?

解决方案

Mahdi here is what this should look like Ref from TreeView.AfterCheck Event

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

// NOTE   This code can be added to the BeforeCheck event handler instead of the AfterCheck event. 
// After a tree node's Checked property is changed, all its child nodes are updated to the same value. 
private void node_AfterCheck(object sender, TreeViewEventArgs e)
{
   // The code only executes if the user caused the checked state to change. 
   if(e.Action != TreeViewAction.Unknown)
   {
      if(e.Node.Nodes.Count > 0)
      {
         /* Calls the CheckAllChildNodes method, passing in the current 
         Checked value of the TreeNode whose checked state changed. */ 
         this.CheckAllChildNodes(e.Node, e.Node.Checked);
      }
   }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top