关闭

asp.net2.0 treeview控件用数据表做为数据源实现n级动态菜单

589人阅读 评论(0) 收藏 举报
  最近做个产品展示网站,本来打算treeview和menu控件数据源用sitemap来实现,但是发现新增产品信息的发布页需要有个 dropdownlist来读取原有的菜单分类,想不出ddl和sitemap如何关联,所以还是改用数据库做为数据源了,参考了网上一些资料,终于实现 treeview的n级动态菜单,写下来做个记录。

写一个递归函数。

vb代码:
程序代码 程序代码

Public Sub PopulateNodes(ByVal nodes As TreeNodeCollection, Optional ByVal intParentID As Int32 = 0)
        Dim showmenu As New ClassLibrary.Jkdata.JkDataBasic ‘创建一个新的类对象
        Dim dt As New DataTable()
        dt = showmenu.GetProduct_Class  ‘获得业务层返回的datatable
        Dim strExpression As String
        strExpression = "[UpID] = " & intParentID
        Dim foundRows() As DataRow
        foundRows = dt.Select(strExpression)
        Dim I As Integer
        Dim PassID As Integer
        For I = 0 To foundRows.GetUpperBound(0)
            Dim tn As New TreeNode()
            tn.Text = foundRows(I).Item("ClassName").ToString()
            tn.Value = foundRows(I).Item("ID").ToString()
            If foundRows(I).Item("UpID") = 0 Then
                tn.NavigateUrl = foundRows(I).Item("Url").ToString‘父分类的页面连接
            Else
                PassID = Convert.ToInt32(foundRows(I).Item("ID"))
                tn.NavigateUrl = foundRows(I).Item("Url") + "?classid=" + PassID.ToString ‘子分类的页面连接含参数传递

            End If

            Dim dr() As DataRow
            dr = dt.Select("[UpID] = " & tn.Value)
            If dr.GetUpperBound(0) > -1 Then
                tn.PopulateOnDemand = True
            End If
            nodes.Add(tn)
        Next
    End Sub

    Protected Sub TreeView1_TreeNodePopulate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeView1.TreeNodePopulate

        PopulateNodes(e.Node.ChildNodes, e.Node.Value)
    End Sub

Page_Load事件中调用函数绑定数据:
程序代码 程序代码

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            PopulateNodes(TreeView1.Nodes, 0)
        End If


aspx页面:
程序代码 程序代码

         <asp:TreeView ID="TreeView1" runat="server" >
         </asp:TreeView>


数据库字段:

ID                自动编号  
UpID            数字
ClassName  文本
Url               文本

最后效果图:




 注:本文转自http://www.morock.net/blog/article.asp?id=76
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:257144次
    • 积分:3599
    • 等级:
    • 排名:第9079名
    • 原创:125篇
    • 转载:15篇
    • 译文:0篇
    • 评论:51条
    文章分类
    最新评论
    JS广告