效果展示:
XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<root id="0" name="左侧导航栏">
<foods id="1" name="食物">
<foods id="11" name="生菜"></foods>
<foods id="12" name="白菜">
<foods id="121" name="大白菜"></foods>
<foods id="122" name="小白菜"></foods>
<foods id="123" name="圆白菜"></foods>
</foods>
</foods>
<fruids id="2" name="水果">
<fruids id="21" name="桃子"></fruids>
<fruids id="22" name="葡萄">
<fruids id="221" name="紫葡萄"></fruids>
</fruids>
</fruids>
<clotheses id="3" name="服饰">
<clotheses id="31" name="鞋子"></clotheses>
<clotheses id="32" name="毛衣"></clotheses>
</clotheses>
</root>
前段代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="GuaidMenu.Index2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>TreeView控件数据绑定之:XML文件数据绑定</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1" ImageSet="Arrows" LineImagesFolder="~/TreeLineImages">
<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="Xmldata.xml"></asp:XmlDataSource>
</div>
</form>
</body>
</html>
注意:TreeView控件的DataSourceID属性的值是XmlDataSource控件ID的值
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace GuaidMenu
{
public partial class Index2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TreeView1.ShowLines = false; //将线显示出来
TreeNodeBinding tnb = new TreeNodeBinding();
tnb.DataMember = "root";
tnb.ValueField = "name";
this.TreeView1.DataBindings.Add(tnb);
TreeNodeBinding tnd = new TreeNodeBinding();
tnd.DataMember = "foods";
tnd.ValueField = "name";
TreeView1.DataBindings.Add(tnd); //将食物绑定到控件上
TreeNodeBinding ftnb = new TreeNodeBinding();
ftnb.DataMember = "fruids";
ftnb.ValueField = "name";
this.TreeView1.DataBindings.Add(ftnb); //将水果绑定到控件上
TreeNodeBinding ctnb = new TreeNodeBinding();
ctnb.DataMember = "clotheses";
ctnb.ValueField = "name";
this.TreeView1.DataBindings.Add(ctnb); //将服饰绑定到控件上
}
}
}
写写博客,方便自己也方便有需要的人*_*!