/// <summary> /// 選擇的節點 /// 塗聚文 20121116 /// 捷為工作室 /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { #region 4 if (e.Action != TreeViewAction.Unknown) { //Event call by mouse or key-press SetNodeCheckStatus(e.Node, e.Node.Checked); } #endregion } /// <summary> /// 選擇的節點 /// </summary> /// <param name="tn"></param> /// <param name="Checked"></param> private void SetNodeCheckStatus(TreeNode tn, bool Checked) { if (tn == null) return; // Check children nodes foreach (TreeNode tnChild in tn.Nodes) { tnChild.Checked = Checked; SetNodeCheckStatus(tnChild, Checked); } // Set parent check status TreeNode tnParent = tn; int nNodeCount = 0; while (tnParent.Parent != null) { tnParent = (TreeNode)(tnParent.Parent); nNodeCount = 0; foreach (TreeNode tnTemp in tnParent.Nodes) if (tnTemp.Checked == Checked) nNodeCount++; if (nNodeCount == tnParent.Nodes.Count) tnParent.Checked = Checked; else tnParent.Checked = false; } } #region 選擇的節點 /// <summary> /// http://www.codeproject.com/Questions/196856/C-NET-Treeview-Node-Checked /// http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aftercheck.aspx /// </summary> /// <param name="treeNode"></param> /// <param name="nodeChecked"></param> public void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked) { foreach (TreeNode node in treeNode.Nodes) { node.Checked = nodeChecked; if (node.Nodes.Count > 0) { this.CheckAllChildNodes(node, nodeChecked); } } } #endregion /// <summary> /// 顯示選擇的節點 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("Uid", typeof(Guid)); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("ParentID", typeof(int)); List<TreeNode> selectedNodes = new List<TreeNode>(); GetSelectedTreeNode(treeView1.Nodes, selectedNodes); int i = 0; foreach (TreeNode node in selectedNodes) { if (!string.IsNullOrEmpty(node.ToolTipText)) { dt.Rows.Add(new Guid(node.ToolTipText), node.Name, node.Text,node.Parent.Name); } i++; } dataGridView1.DataSource = dt; } /// <summary> /// 選擇的節點的值 /// </summary> /// <param name="nodes"></param> /// <param name="selectedNodes"></param> void GetSelectedTreeNode(TreeNodeCollection nodes, List<TreeNode> selectedNodes) { foreach (TreeNode node in nodes) { if (node.Checked) { selectedNodes.Add(node); } GetSelectedTreeNode(node.Nodes, selectedNodes); } }