在TreeView中一次检查一个节点

时间:2013-01-12 08:54:43

标签: c# winforms treeview treenode oncheckedchanged

我从数据库中填充了TreeView,其中包含大量节点,每个节点可能有一些子节点,并且没有固定的角色,如2个depthes,它可能非常深。

想象一下,TreeView CheckBoxesRadioButtons,我希望我的TreeView一次只有一个已检查的节点。我尝试了AfterCheckBeforeCheck事件,但它们会陷入永久循环,我该怎么办?

我想保持我的已检查节点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);
    }
}

1 个答案:

答案 0 :(得分:3)

迈赫迪这里应该是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);
      }
   }
}