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

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

最近做个产品展示网站,本来打算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

你可能感兴趣的:(UI,asp.net,asp,vb,VB.NET)