简体   繁体   中英

What algorithm is used in this code?

This code checks and unchecks the child nodes of a treeview control. What algorithm is used in this code?

private int _callCountUp;

private int _callCountDn;

private void tvwPermissions_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            bool anyChecked = false;

            if (_callCountDn == 0 && e.Node.Parent != null)
            {
                anyChecked = false;
                foreach (TreeNode childNode in e.Node.Parent.Nodes)
                {
                    if (childNode.Checked)
                    {
                        anyChecked = true;
                        break;
                    }
                }
                _callCountUp += 1;

                if (anyChecked)
                    e.Node.Parent.Checked = true;

                _callCountUp -= 1;
            }

            if (_callCountUp == 0)
            {
                foreach (TreeNode childNode in e.Node.Nodes)
                {
                    _callCountDn += 1;
                    childNode.Checked = e.Node.Checked;
                    _callCountDn -= 1;
                }
            }
        }

Not so sure this has a name. It is quite standard, the _callCountUp/Dn fields avoid trouble when changing the Checked property of a node causes the AfterCheck event handler to run again. StackOverflow is a very typical outcome when the event handler recurses without bound.

The generic pattern resembles this:

private bool modifyingNodes;

private void treeview_AfterCheck(object sender, TreeViewEventArgs e) {
    if (modifyingNodes) return;
    modifyingNodes = true;
    try {
       // etc..
    }
    finally {
       modifyingNodes = false;
    }
}

The finally block ensures that a handled exception (such as through ThreadExceptionDialog) doesn't permanently leave the state variable set to true. It's optional of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM