在平常开发中,treeview的节点显示checkbox,若节点存在几级时,往往希望,选中父节点后,其子节点都要选中,如何实现勒,请看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SmartHome
{
public partial class TreeViewAndCheckbox : Form
{
public TreeViewAndCheckbox()
{
InitializeComponent();
//treeview显示checkbox
treeView1.CheckBoxes = true;
TreeViewUtil.ShowTreeViewInfo(treeView1);
this.treeView1.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck);
}
private void TreeViewAndCheckbox_Load(object sender, EventArgs e)
{
treeView1.ExpandAll();
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
textBox1.Text = e.Node.Text;
if (e.Node.Checked)
{
//取消节点选中状态之后,取消所有父节点的选中状态
setChildNodeCheckedState(e.Node, true);
}
else
{
//取消节点选中状态之后,取消所有父节点的选中状态
setChildNodeCheckedState(e.Node, false);
//如果节点存在父节点,取消父节点的选中状态
if (e.Node.Parent != null)
{
setParentNodeCheckedState(e.Node, false);
}
}
}
}
//取消节点选中状态之后,取消所有父节点的选中状态
private void setParentNodeCheckedState(TreeNode currNode, bool state)
{
TreeNode parentNode = currNode.Parent;
parentNode.Checked = state;
if (currNode.Parent.Parent != null)
{
setParentNodeCheckedState(currNode.Parent, state);
}
}
//选中节点之后,选中节点的所有子节点
private void setChildNodeCheckedState(TreeNode currNode, bool state)
{
TreeNodeCollection nodes = currNode.Nodes;
if (nodes.Count > 0)
foreach (TreeNode tn in nodes)
{
tn.Checked = state;
setChildNodeCheckedState(tn, state);
}
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
foreach (TreeNode tn in treeView1.Nodes)
{
if (tn.Checked)
i++;
foreach (TreeNode item in tn.Nodes)
{
if (item.Checked)
{
i++;
}
foreach (TreeNode nd in item.Nodes)
{
if (nd.Checked)
{
i++;
}
}
}
textBox2.Text = i.ToString();
}
}
/// <summary>
/// 查询treeNode节点下有多少节点被选中(递归实现,不受级数限制)
/// </summary>
/// <param name="tv"></param>
/// <returns></returns>
private int GetNodeChecked(TreeNode tv)
{
int x = 0;
if (tv.Checked)
{
x++;
}
foreach (TreeNode item in tv.Nodes)
{
x+= GetNodeChecked(item);
}
return x;
}
/// <summary>
/// 查询TreeView下节点被checked的数目
/// </summary>
/// <param name="treev"></param>
/// <returns></returns>
private int GetTreeViewNodeChecked(TreeView treev)
{
int k = 0;
foreach (TreeNode item in treev.Nodes)
{
k += GetNodeChecked(item);
}
return k;
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = GetTreeViewNodeChecked(treeView1).ToString();
}
}
}