Henry Instructions - VB.NET Dynamic Load TreeView Node (2)
Han Rui (2003.4.13)
2. Add a child node when you click
Click on TreeView, for the TreeView control itself, does not write a click (selection) event handler for the TreeView control, but write all the click events of all nodes into an AfTerselect event. Therefore, before writing a program that click Add to join the child node, we must also write a method of finding which level node that looks a click node.
Public Function NodeEvel (Byval n as treenode) as Byte
'* Find the number of current nodes in the tree
DIM I as byte = 1
DIM M as string
Do untric n.parent is nothing
n = n.parent
i = 1
Loop
Return I
END FUNCTION
With this function, you can easily get the level of the node. Now we can safely write nodes to select event handles to achieve dynamically load sub-nodes of each level.
Private sub treeview1_afterselect (Byval e as system.Windows.Forms.treeViewEventArgs) Handles TreeView1.AfTerselectElectlectElectr
Select Case Nodeevel (E.NODE) .tostring
Case "1"
IF E.Node.GetnodeCount (false) = 0 THEN
MyCommand.commandtext = "SELECT first level child node number, first level child node name from first level child node WHERE root node number = '" & e.node.tag & "'"
Fill_treeeleaf ()
END IF
Case "2"
IF E.Node.GetnodeCount (false) = 0 THEN
MyCommand.commandtext = "SELECT Second Level Sub Node Number, Second Level Sub Name" The second level child Node WHERE first child node number = '"& e.node.tag &"' "
Fill_treeeleaf ()
END IF
End SELECT
End Sub
Public Sub Fill_TreeEleaf ()
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 exception
MSGBOX (ex.Message)
Finally
MyConnection.Close ()
END TRY
End Sub
Ok, now take a look at the results of the click, as shown in Figures 2 and 3.
Note: Please be familiar with the role of Text and Tag, which will reach a good effect. ----
Disclaimer: The right to copyright and interpretation of this article belongs to Han Rui, if you need to reprint, please keep your full content and this statement.
QQ: 18349592
E-mail: Henry7685@hotmail.com
Please visit my column: http://www.9cbs.net/develop/author/netauthor/latitude/