Vb. Implementation of hierarchical data binding TreeView in Net

Source: Internet
Author: User
Tags filter bind exit count integer key
treeview| data Summary:In VB6, the TreeView is often used to represent hierarchical data, but the related code that interacts with the database requires a lot of manual coding; In vb.net, because of the enhancement of the data binding function and the enhancement of language features, it is easy to bind the TreeView to the hierarchical data, this article will first establish a dbtreeview that inherits from the TreeView and then use a unit (department) 's hierarchical data is bound to Dbtreeview and provides code to interact with the database.

   1, from the level of data to express the way to start

In this example, the Department table (Department) has five fields, such as the following table:

Field name Field Type description
Id Automatic numbering Key
Code String Coding
Name String Name
Pid Int ID of parent Node
CPtr Boolean Do you have any child nodes?
  
2, inherit from the TreeNode Mytreenode

In Mytreenode, three new properties are added, such as the following table:

Property name Type Description
Value Object Key
Pid Object ID of parent Node
CPtr Boolean Do you have any child nodes?
  
In the Init event, set the three properties and the Text property, based on the four parameters passed in.

3, bind the Dbtreeview to the data source

Property name Type Description
Datasource DataView Dbtreeview data sources use DataView instead of object
Value Member String value member (column name of data source [DataView])
Display Member string display (in text) member
Pid Member String Parent ID Member
CPtr Member Whether string has child nodes
  
The latter four attributes correspond to the Mytreenode value,text,pid,cptr.

The relevant code is as follows:

Protected Property DataSource () as Object
Get
Return Mdataview
End Get

Set (ByVal Value as Object)
If Value is nothing Then
Else
Mdataview = Value
CM = CType (Me.BindingContext (Mdataview), CurrencyManager)
Updatetreeview ()
End If
End Set
End Property

Protected Property Pidmember () as String
Get
Return Mpidmember
End Get
Set (ByVal Value as String)
Mpidmember = Value
End Set
End Property

Protected Property DisplayMember () as String
Get
Return Join (Mdisplaymember, Splitchar)
End Get
Set (ByVal Value as String)
Mdisplaymember = Split (Value, Splitchar)
End Set
End Property

' Note that these properties are protected members and must be set in the Init event:

Public Sub Init (ByVal dispmember As String, ByVal ValueMember as String, ByVal Pidmember as String, ByVal Cptrmember as St Ring, ByVal datasource as DataView)
Me.valuemember = ValueMember
Me.displaymember = Dispmember
Me.pidmember = Pidmember
Me.cptrmember = Cptrmember
Me.datasource = DataSource
' Maximum value, the new will be value+1, to ensure that the value of the key.
Me.mDataView.Sort = Me.valuemember
Me.m_maxid = Me.getvalue (me.mdataview.count-1)
End Sub
Format the DisplayMember property such as: Field 1; field 2; Field 3 ..., when setting properties, converts the arguments passed to a string array mdisplaymember and returns data such as: value 1 value 2 value 3 ...

Protected Overridable Function getdisplay (ByVal Index as Integer) as Object
Dim I as Integer
Dim temp as String = ""
For i = 0 to Mdisplaymember.length-1
Temp = temp & IIf (i > 0, Linkchar, "") & Mdataview (Index) (Mdisplaymember (i))
Next
Return Temp
End Function


Other functions that retrieve values see source programs.

   Spanning Tree

Updatetreeview calls the private method Filltree to generate the tree, it is to be noted that Filltree simply generates the child nodes of the specified node and adds them to the specified node, rather than adding all nodes to the tree at once, if no nodes are specified (the first time it is populated), Just add the top-level node.

Private Sub Filltree (ByRef pnode as Mytreenode, Optional ByVal filter as String = "")
Mdataview.rowfilter = Filter
Dim i As Integer, Icol as Integer
Dim NewNode as Mytreenode
RemoveHandler cm. PositionChanged, AddressOf cm_positionchanged
Me.beginupdate ()
For i = 0 to Mdataview.count ()-1
NewNode = New Mytreenode (Getdisplay (i), GetValue (i), getpid (i), getcptr (i))
' When there are child nodes, add a null node for this node.
If NewNode. CPtr Then
Dim Nullnode as New Mytreenode ()
Nullnode. Value = Noexpandnodevalue
NewNode. Nodes.Add (Nullnode)
End If
If Pnode is nothing Then
Me.Nodes.Clear ()
ME.NODES.ADD (NewNode)
Else
Pnode. Nodes.Add (NewNode)
End If
Next
Me.endupdate ()
Mdataview.rowfilter = ""
AddHandler cm. PositionChanged, AddressOf cm_positionchanged
End Sub
Before the node is expanded, all the child nodes are deleted and Filltree is added to the node to be expanded.

Private Sub Dbtreeview_beforeexpand (ByVal sender as Object, ByVal e as System.Windows.Forms.TreeViewCancelEventArgs) Handles Mybase.beforeexpand
' When the new node causes the BeforeExpand event, exit directly.
If Expandwhenaddnode Then Exit Sub
' Update the child node before expanding the node.
Dim CurrentNode as Mytreenode = CType (E.node, Mytreenode)
With CurrentNode
. Nodes.clear ()
Filltree (CurrentNode, mpidmember & "=" & CInt (. Value))
End With
End Sub
4, the implementation of data and bound control synchronization

To achieve synchronization of two aspects:

1. Other bound controls, such as a textbox, should be consistent with the record where the current node of the TreeView points.

Private Sub Dbtreeview_afterselect (ByVal sender as Object, ByVal e as System.Windows.Forms.TreeViewEventArgs) Handles MyB Ase. AfterSelect

If E.node is nothing Then Exit Sub
' Locate to position
Cm. Position = GetPosition (CType (E.node, Mytreenode). Value)
If AllowEdit Then
OldNode = E.node
Oldpos = cm. Position
End If
End Sub
2. When other bound controls change the data source, the tree node is updated, and this work occurs when the CurrencyManager positionchanged event is triggered.

Public Sub cm_positionchanged (ByVal sender as Object, ByVal e as System.EventArgs)
If CType (Me.selectednode, Mytreenode). Value <> GetValue (cm. Position) Then
Debug.WriteLine ("Current node isn ' t correct to currencymanager.position!")
Me.selectednode = Findnodebyvalue (GetValue (cm. Position), Me.nodes)
End If
If AllowEdit Then
If Me.selectednode is nothing AndAlso cm. Position = cm. Count-1 Then
' When new records are added, the tree node is added.
If CType (cm. Current, DataRowView). IsNew Then
Me.selectednode = AddNode (cm. Position)
Exit Sub
End If
End If
If not OldNode are nothing Then
If CType (OldNode, Mytreenode). Value = GetValue (oldpos) Then
' Update the old knot.
Oldnode.text = Getdisplay (Oldpos)
Else
End If
End If
End If
End Sub
   using Dbtreeview

After the program runs the interface is as follows:



Related code See source program, here is not detailed, it should be noted that the deletion does not delete the child node, just delete the current node, the deletion of child nodes should be implemented recursively in the stored procedure, and should not be placed in the front-end.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.