TreeView的节点选择问题
从网上下载了一个类,使用后发现有问题:
C# code
public static class TreeViewCheck
{
/// <summary>
/// 系列节点 Checked 属性控制
/// </summary>
/// <param name="e"></param>
public static void CheckControl(TreeViewEventArgs e)
{
if (e.Action != TreeViewAction.Unknown)
{
if (e.Node != null && !Convert.IsDBNull(e.Node))
{
CheckParentNode(e.Node);
if (e.Node.Nodes.Count > 0)
{
CheckAllChildNodes(e.Node, e.Node.Checked);
}
}
}
}
#region 私有方法
//改变所有子节点的状态
private static void CheckAllChildNodes(TreeNode pn, bool IsChecked)
{
foreach (TreeNode tn in pn.Nodes)
{
tn.Checked = IsChecked;
if (tn.Nodes.Count > 0)
{
CheckAllChildNodes(tn, IsChecked);
}
}
}
//改变父节点的选中状态,此处为所有子节点不选中时才取消父节点选中,可以根据需要修改
private static void CheckParentNode(TreeNode curNode)
{
bool bChecked = false;
if (curNode.Parent != null)
{
foreach (TreeNode node in curNode.Parent.Nodes)
{
if (node.Checked)
{
bChecked = true;
break;
}
}
if (bChecked)
{
curNode.Parent.Checked = true;
CheckParentNode(curNode.Parent);
}
else
{
curNode.Parent.Checked = false;
CheckParentNode(curNode.Parent);
}
}
}
#endregion
}
会出现如下图的错误:
无法显示图片。
需要再次点击才能生效。请高手帮忙看看这个类,应该怎么改。谢谢!
------解决方案--------------------
protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
SetChildChecked(e.Node);
if (!e.Node.Value.Equals("0"))
{
SetParentChecked(e.Node);
}
}
private void SetChildChecked(TreeNode parentNode)
{
foreach (TreeNode node in parentNode.ChildNodes)
{
node.Checked = parentNode.Checked;
if (node.ChildNodes.Count > 0)
{
SetChildChecked(node);
}
}
}
private void SetParentChecked(TreeNode childNode)
{
TreeNode parentNode = childNode.Parent;
if (parentNode != null)
{
if (!parentNode.Checked && childNode.Checked)
{
parentNode.Checked = true;
}
else if (parentNode.Checked && !childNode.Checked)
{
int checks = 0;
foreach (TreeNode node in parentNode.ChildNodes)
{
if (node.Checked)
{
checks++;
break;
}
}
if (checks == 0)
{
parentNode.Checked = false;
if (!parentNode.Value.Equals("0"))
{
SetParentChecked(parentNode);
}
}
}
}
}
private void NodeCheck(TreeNode TNode)
{
bool bFlag = false;
if (TNode != null)
{
if (TNode.Checked)
{
if (TNode.ChildNodes.Count > 0)
{
for (int i = 0; i < TNode.ChildNodes.Count; i++)
TNode.ChildNodes[i].Checked = true;
}
if (TNode.Parent != null)
TNode.Parent.Checked = true;
}
else
{
if (TNode.ChildNodes.Count > 0)
{
for (int i = 0; i < TNode.ChildNodes.Count; i++)
TNode.ChildNodes[