TreeView控件与XML的绑定

1.xml的格式如下:

<?xml version="1.0" encoding="utf-8" ?>
<root name="Digital RainWater" img="image\home.gif">
<subroot name="East China" img="image\resource_go.gif" nos="1">
    <contont url="1.html">General Info</contont>
    <contont url="1.html">Person</contont>
    <contont url="1.html">Nation</contont>
    <contont url="1.html">Area</contont>  
</subroot>
<subroot name="North China" img="image\crm.gif" nos="2">
    <contont url="1.html">Original Data</contont>
    <contont url="1.html">Dairly Report</contont>
    <contont url="1.html">Diary</contont>
    <contont url="1.html">Relationship</contont>   
</subroot>
<subroot name="South China" img="image\salary.gif" nos="3">
    <contont url="1.html">Dynamic Data</contont>
    <contont url="1.html">Information</contont>  
</subroot>
<subroot name="User Info" img="image\meeting.gif" nos="4">
    <contont url="1.html">New User</contont>
    <contont url="1.html">Registerd User</contont>
    <contont url="1.html">Modify Password</contont>   
</subroot>
</root>

2:前台:

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %> 

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:TreeView ID="TreeView2" Target="mainFrame" ForeColor="#215dc6" NodeIndent="5" runat="server" ShowLines="true" DataSourceID="XmlDataSource1" ExpandDepth="1" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged" OnDataBound="TreeView1_DataBound" >
        <NodeStyle NodeSpacing="0px" HorizontalPadding="5px" VerticalPadding="0" />
        <RootNodeStyle CssClass="special" />
        <ParentNodeStyle CssClass="special" />
        <SelectedNodeStyle ForeColor="red"/>
        </asp:TreeView>
    </ContentTemplate>
      </asp:UpdatePanel>
       
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/App_Data/XMLFile.xml">
        </asp:XmlDataSource>

3.后台.cs代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TreeView2Bind();
        }
    }

    public void TreeView2Bind()
    {
        TreeNodeBinding root = new TreeNodeBinding();
        root.DataMember = "root";
        root.ValueField = "name";
        root.ImageUrlField = "img";
        //root.NavigateUrlField = "url";
        this.TreeView2.DataBindings.Add(root);

        TreeNodeBinding subroot = new TreeNodeBinding();
        subroot.DataMember = "subroot";
        subroot.ValueField = "nos";
        subroot.TextField = "name";
        subroot.ImageUrlField = "img";
        this.TreeView2.DataBindings.Add(subroot);

        TreeNodeBinding content = new TreeNodeBinding();
        content.DataMember = "contont";
        content.ValueField = "#InnerText";
        content.NavigateUrlField = "url";
        this.TreeView2.DataBindings.Add(content);
        //this.TreeView1.ShowExpandCollapse = false;
    }

你可能感兴趣的:(treeview)