在TreeView中使用CheckBox
阿新 • • 發佈:2017-10-18
c# treeview checkbox
實現C# TreeView的AfterCheck事件中的Checked,主要有以下情況: 1.父節點勾選則子節點全部勾選 2.父節點不勾選則子節點全部不勾選 3.子節點全部不勾選則父節點不勾選 4.子節點部分勾選則父節點不勾選 5.子節點全部勾選則父節點被勾選 以下是遞歸實現
private void SetNodeCheckStatus(TreeNode tn, bool chk) { if (tn == null) return; // Set child nodes check status foreach( TreeNode tnChild in tn.Nodes) { tnChild.Checked = chk; SetNodeCheckStatus(tnChild, chk); } // Set parent check status int nNodeCount = 0; TreeNode tnParent = tn; while(tnParent.Parent != null) { nNodeCount = 0; tnParent = tnParent.Parent; foreach(TreeNode tnTmp in tnParent.Nodes) { if (tnTmp.Checked == chk) { nNodeCount++; } } if (nNodeCount == tnParent.Nodes.Count) tnParent.Checked = chk; else tnParent.Checked = false; } }
在TreeView中使用CheckBox