2013-01-12 55 views
0

我有一個TreeView由擁有很多節點的數據庫填充,並且每個節點可能有一些子節點,並且沒有像2個depthes那樣的固定角色,它可能非常深。在TreeView中每次檢查一個節點

想象一下,TreeViewCheckBoxesRadioButtons,我想我的TreeView只是一次有一個checked節點。我已嘗試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); 
    } 
} 
+2

馬赫迪將更好地服務於你,如果你發佈的信息代碼,你目前有在手,涉及到您的問題.. – MethodMan

+0

我認爲你在正確的方向牽制。發佈您的代碼。 – Rafal

+0

請顯示你的'private void node_AfterCheck(object sender,TreeViewEventArgs e)'你需要2個事件,這個我只是突出顯示,還有一個方法Signature就像這樣'private void CheckAllChildNodes(TreeNode treeNode,bool nodeChecked)'來檢查if父節點有ChildNodes.Checked,你需要做一個foreach循環,然後等待你發佈你的代碼。 – MethodMan

回答

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); 
     } 
    } 
} 
+0

+1。感謝DJ KRAZE,我所需要的只是'e.Action!= TreeViewAction.Unknown'。多一點改變它的工作。祝你好運。 –

+0

Mahdi很高興我能指出您的正確參考祝您好運 – MethodMan

相關問題