原文
Display Hierarchical Data with TreeView in ASP.NET 2.0
不同的 应用有不同的很多种方法
数据库结构如下
不同的 应用有不同的很多种方法
数据库结构如下
控件
<asp:TreeView
ID="TreeView1"
ExpandDepth="0"
PopulateNodesFromClient="true"
ShowLines="true"
ShowExpandCollapse="true"
runat="server" />
后端代码
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
PopulateRootLevel()
End If
End Sub
Private Sub PopulateRootLevel()
Dim objConn As New SqlConnection(_
"server=JOTEKE/SQLExpress;Trusted_Connection=true;DATABASE=TreeViewSampleDB")
Dim objCommand As New SqlCommand("select id,title,(select count(*) FROM SampleCategories " _
& "WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID IS NULL", _
objConn)
Dim da As New SqlDataAdapter(objCommand)
Dim dt As New DataTable()
da.Fill(dt)
PopulateNodes(dt, TreeView1.Nodes)
End Sub
Private Sub PopulateNodes(ByVal dt As DataTable, _
ByVal nodes As TreeNodeCollection)
For Each dr As DataRow In dt.Rows
Dim tn As New TreeNode()
tn.Text = dr("title").ToString()
tn.Value = dr("id").ToString()
nodes.Add(tn)
'If node has child nodes, then enable on-demand populating
tn.PopulateOnDemand = (CInt(dr("childnodecount")) > 0)
Next
End Sub
Private Sub PopulateSubLevel(ByVal parentid As Integer, _
ByVal parentNode As TreeNode)
Dim objConn As New SqlConnection(_
"server=JOTEKE/SQLExpress;Trusted_Connection=true;DATABASE=TreeViewSampleDB")
Dim objCommand As New SqlCommand("select id,title,(select count(*) FROM SampleCategories " _
& "WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID=@parentID", _
objConn)
objCommand.Parameters.Add("@parentID", SqlDbType.Int).Value = parentid
Dim da As New SqlDataAdapter(objCommand)
Dim dt As New DataTable()
da.Fill(dt)
PopulateNodes(dt, parentNode.ChildNodes)
End Sub
这个是树节点展开事件代码
Protected Sub TreeView1_TreeNodePopulate(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeView1.TreeNodePopulate
PopulateSubLevel(CInt(e.Node.Value), e.Node)
End Sub