0

TreeView从数据库中填充了很多节点,每个节点可能有一些子节点,并且没有像 2 个深度这样的固定角色,它可能非常深。

想象一下,我希望我一次TreeView CheckBoxes只检查一个节点。我已经尝试过事件,但它们陷入了永远的循环,我该怎么办?RadioButtonsTreeViewAfterCheckBeforeCheck

我想保持我选中的节点 CHECKED 并取消选中所有其他节点,但我不能。等待你的聪明点。谢谢。

这是我尝试过但最终出现StackOverFlow异常的代码,我想它可能是在说去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);
    }
}
4

1 回答 1

4

Mahdi 这应该是TreeView.AfterCheck 事件中的 Ref

// 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);
      }
   }
}
于 2013-01-12T09:41:12.890 回答