前台HTML:
<asp:TreeView ID="TreeViewMU" runat="server" ShowCheckBoxes="All" AutoGenerateDataBindings="False" ontreenodecheckchanged="TreeViewMU_TreeNodeCheckChanged">
</asp:TreeView>
后台CS:
-----------绑定TreeView--------------------------------------------------------------------------
protected void TreeVMU()
{
XmlDocument xmldoc = new XmlDocument();
string spath = Server.MapPath("~\\xml\\navigation.xml");
xmldoc.Load(spath);
TreeViewMU.Nodes.Clear();
TreeViewMU.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));
TreeNode tnode = new TreeNode();
tnode = (TreeNode)TreeViewMU.Nodes[0];
addTreeNode(xmldoc.DocumentElement,tnode);
//TreeViewMU.ExpandAll();
}
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;//存放xml节点
TreeNode tNode;//存放树节点
XmlNodeList xNodeList;//存放节点集合(这里是所有子节点的集合)
if (xmlNode.HasChildNodes)//判断是否有子节点
{
xNodeList = xmlNode.ChildNodes;//子节点集合
for (int i = 0; i <= xNodeList.Count - 1; i++)
{
xNode = xmlNode.ChildNodes[i]; //获取当前子节点
TreeNode node = new TreeNode();
node.Text = xNode.Attributes["Name"].Value;
treeNode.ChildNodes.Add(node);
tNode = treeNode.ChildNodes[i];//获取当前树节点
addTreeNode(xNode, tNode); //递归
}
}
else
{
treeNode.Text = xmlNode.Attributes["Name"].Value;
}
}
--------------------------选择Checkbox---------------------------------------------------
private void CheckTreeNode(TreeNode treeNode,bool tf)
{
TreeNode tNode;//存放树节点
if (treeNode.ChildNodes.Count>0)//判断是否有子节点
{
for (int i = 0; i <= treeNode.ChildNodes.Count - 1; i++)
{
tNode = (TreeNode)treeNode.ChildNodes[i]; //获取当前子节点
tNode.Checked = tf;
CheckTreeNode(tNode, tf); //递归
}
}
else
{
treeNode.Checked = tf;
}
}
protected void TreeViewMU_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
if (TreeViewMU.CheckedNodes.Count > 0)
{
if (e.Node.Checked == true)
{
e.Node.Checked = true;
CheckTreeNode(e.Node, true);
}
else
{
e.Node.Checked = false;
CheckTreeNode(e.Node, false);
}
}
}
效果图:
简单明了。