winForm中应用带CheckBox的TreeView
如题;
1、如何实现当子节点全部选中/取消,则父节点选中/取消
2、如何实现当父节点选中/取消,则子节点全部选中/取消
哪位能慷慨相助,最好能有源码实例,先谢谢了!
---------------------------------------------------------------
private void treeView1_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if(e.Action != TreeViewAction.Unknown)
{
CheckAllChildNodes(e.Node,e.Node.Checked);
//选中父节点
bool bol=true;
if(e.Node.Parent !=null)
{
for(int i=0;i<e.Node.Parent.Nodes.Count;i++)
{
if(!e.Node.Parent.Nodes[i].Checked)
bol = false;
}
e.Node.Parent.Checked = bol;
}
}
}
//选中子节点
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);
}
}
}
---------------------------------------------------------------
1、如何实现当子节点全部选中/取消,则父节点选中/取消
楼主是想子节点都选中的时候,所有的父节点都选中吗?如果是的话稍微改一下即可
private void treeView1_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if(e.Action != TreeViewAction.Unknown)
{
CheckAllChildNodes(e.Node,e.Node.Checked);
//选中父节点
bool bol=true;
if(e.Node.Parent !=null)
{
for(int i=0;i<e.Node.Parent.Nodes.Count;i++)
{
if(!e.Node.Parent.Nodes[i].Checked)
bol = false;
}
TreeNode tn=e.Node;
while ( tn.Parent != null )
{
tn = tn.Parent;
tn.Checked = bol;
}
tn.Checked = bol;
}
}
}