Asp.net源码交流论坛 Asp.net交流讨论区Asp.ne技术问答在TreeView中操作节点CheckBox需要注意的

1  /  1  页    1  跳转
发表新主题 回复该主题

标题: 在TreeView中操作节点CheckBox需要注意的

身份:学员

 
  • UID:3066
  • 来自:
  • 精华:0
  • 积分:3
  • 帖子:3
  • 注册: 2007-12-20
  • 状态: 离线
  • 威望:0.00
  • 金钱:0.45 元

在TreeView中操作节点CheckBox需要注意的

最近应网友要求,写一个Demo程序来演示在TreeView中,选中某个节点,使其子节点全部选中,父节点则根据当前节点变化而进行变更状态。我在实现的时候,想当然在TreeView的AfterCheck事件去做,但是已运行程序,则发现程序溢出了,仔细一看,原来是在修改某个节点的Checked属性时,使得TreeView的AfterCheck事件再次相应,从而造成连锁反应。通过事件参数,可以得到Action属性,查看msdn后,才发现应该在事件中对Action要进行判断,从而避免连锁反应。

大致的方法如下:


private void trvDBBinding_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
    if( e.Action != TreeViewAction.Unknown )
    {
        //Event call by mouse or key-press
        SetNodeCheckStatus( e.Node, e.Node.Checked );
    }
}

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;
    }
}


与此类似的事件,还有AfterCollapse、 AfterExpand、 AfterSelect这三个,因此避免事件的连锁反应,一定要对Action进行判断。

Tags功能还挺好用~~:LöΟ—ñ2Ûbbs.51aspx.comÚZ¬°)!>l-H
引用 回复
 

身份:学员

 
  • UID:21845
  • 来自:
  • 精华:0
  • 积分:1
  • 帖子:1
  • 注册: 2008-06-12
  • 状态: 离线
  • 威望:0.00
  • 金钱:0.10 元

回复:在TreeView中操作节点CheckBox需要注意的

之前以为要用before事件cancel,原来是靠action屏蔽掉连锁反应 ,感谢楼主的文章:LöΟ—ñ2Ûbbs.51aspx.comÚZ¬°)!>l-H
引用 回复
 
1  /  1  页    1  跳转
发表新主题 回复该主题

现在时间是:2008-11-24 02:02:35 京ICP备06046876号