c#,winform,treeview,选中节点,选中相应的全部子节点,取消节点,取消父节点
时间:2011-02-18 来源:leiOOlei
如图所示:
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication6
{
public partial class TreeViewTest : Form
{
public TreeViewTest()
{
InitializeComponent();
}
private void TreeViewTest_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);
}
}
}
}
相关阅读 更多 +