转自:http://bbs.csdn.net/topics/340213279
//选中一个节点时同时其父节点也选中
private void tvMenu_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Node.Checked)
{
if (e.Node.Parent != null)
{
if (e.Node.Parent.Parent != null)
{
if (e.Node.Parent.Parent.Parent != null)
{
e.Node.Parent.Parent.Parent.Checked = true;
}
e.Node.Parent.Parent.Checked = true;
}
e.Node.Parent.Checked = true;
}
}
else
{
bool found1 = false;
bool found2 = false;
bool found3 = false;
if (e.Node.Parent != null)
{
if (e.Node.Parent.Parent != null)
{
if (e.Node.Parent.Parent.Parent != null)
{
foreach (TreeNode tn in e.Node.Parent.Parent.Parent.Nodes)
{
if (tn.Checked == true)
{
found1 = true;
break;
}
}
if (found1 == false)
e.Node.Parent.Parent.Parent.Checked = false;
}
foreach (TreeNode tn in e.Node.Parent.Parent.Nodes)
{
if (tn.Checked == true)
{
found2 = true;
break;
}
}
if (found2 == false)
e.Node.Parent.Parent.Checked = false;
}
foreach (TreeNode tn in e.Node.Parent.Nodes)
{
if (tn.Checked == true)
{
found3 = true;
break;
}
}
if (found3 == false)
e.Node.Parent.Checked = false;
}
}
}
//选中一个节点时同时其子节点全部选择中
private void tvMenu_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Node.Nodes.Count > 0)
{
foreach (TreeNode ChildNode in e.Node.Nodes)
{
ChildNode.Checked = e.Node.Checked;
}
}
}