** Henry ** ** 手记- VB.NET ** ** 中动态加载 Treeview ** ** 节点(二) **
韩睿 (2003.4.13)
** 2. ** ** 点击时加入子节点 ** ** **
对 TreeView 的点击,对于 TreeView 控件本身,并没有为哪一个级别的 Node 编写点击(选择)事件处理程序,而是把所有节点的点击事件都写入了一个 AfterSelect 事件中。因此,在编写点击加入子节点的程序之前,我们还必须编写一个查找点击的节点是哪一级节点的方法。
Public Function NodeLevel( ByVal n As TreeNode) As Byte
'* 找出树中当前节点的级数
Dim i As Byte = 1
Dim m As String
Do Until n.Parent Is Nothing
n = n.Parent
i += 1
Loop
Return i
End Function
通过这个函数,就可以很方便地得到节点的级别。现在我们可以放心地编写节点选择事件处理程序,以实现动态加载各级节点的子节点。
Private Sub TreeView1_AfterSelect( ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
Select Case NodeLevel(e.Node).ToString
Case "1"
If e.Node.GetNodeCount( False ) = 0 Then
mycommand.CommandText = "select 第一级子节点编号,第一级子节点名称 from 第一级子节点 where 根节点编号 ='" & e.Node.Tag & "'"
fill_treeleaf()
End If
Case "2"
If e.Node.GetNodeCount( False ) = 0 Then
mycommand.CommandText = "select 第二级子节点编号,第二级子节点名称 from 第二级子节点 where 第一级子节点编号 ='" & e.Node.Tag & "'"
fill_treeleaf()
End If
End Select
End Sub
Public Sub fill_treeleaf()
mycommand.Connection = myconnection
Try
myconnection.Open()
Dim mysqlreader As OleDb.OleDbDataReader = mycommand.ExecuteReader
While mysqlreader.Read()
Dim tree_leaf As New TreeNode()
tree_leaf.Tag = mysqlreader.GetString(0)
tree_leaf.Text = mysqlreader.GetString(1)
TreeView1.SelectedNode.Nodes.Add(tree_leaf)
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
myconnection.Close()
End Try
End Sub
好了,现在来看看点击的结果,如图 2和图3所示。
Note: 请大家要熟悉 Text 与 Tag 的作用,在使用时会达到很好的效果。
----
声明:本文版权与解释权归韩睿所有,如需转载,请保留完整的内容及此声明。
QQ: 18349592
E-Mail: [email protected]
请访问本人专栏: http://www.csdn.net/develop/author/netauthor/Latitude/