Rambler's Top100
Главная
Новости
Статьи
Форумы
Книги
Коды
Сообщество
Блоги
О нас
 

Логин

Email:
  Пароль:

Войти
Зарегистрироваться
Забыл пароль

Поиск

 Искать :
 
Вперед

Книги по теме

Искать:
в:
Порядок:

Исходник

Автор:

lagep

 
Название:

Заполнение TreeView иерархическими данными (Класс VB.NET 2.0)

Дата: 16 February 2006
Описание: Данный класс предназначен для содания объекта, позволяющего заполнить управляющий элемент System.Windows.Forms.TreeView данными из базы данных в фомате: MemberID, ParentMemberID, MemberNamе. Стандартная задача отображения иерархического набора данных в виде дерева.  
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=184]Заполнение TreeView иерархическими данными (Класс VB.NET 2.0)[/CODEPOST]
Оценка: Проголосовало 16 посетителей, средняя оценка 3.88
Оценить:
  1 Imports System.Collections.Generic
  2 
  3 Public Class HierarchyMemberClass
  4     Private m_MemberID As Integer
  5     Private m_ParentMemberID As Integer
  6     Private m_MemberName As String
  7 
  8     Public Property MemberID() As Integer
  9         Get
 10             Return m_MemberID
 11         End Get
 12         Set(ByVal value As Integer)
 13             m_MemberID = value
 14         End Set
 15     End Property
 16 
 17     Public Property ParentMemberID() As Integer
 18         Get
 19             Return m_ParentMemberID
 20         End Get
 21         Set(ByVal value As Integer)
 22             m_ParentMemberID = value
 23         End Set
 24     End Property
 25 
 26     Public Property MemberName() As String
 27         Get
 28             Return m_MemberName
 29         End Get
 30         Set(ByVal value As String)
 31             m_MemberName = value
 32         End Set
 33     End Property
 34     Sub New(ByVal MemberID As Integer, ByVal ParentMemberID As Integer, ByVal MemberName As String)
 35         m_MemberID = MemberID
 36         m_ParentMemberID = ParentMemberID
 37         m_MemberName = MemberName
 38     End Sub
 39 End Class
 40 
 41 Public Class FillHierarchyTreeClass
 42     Private m_TreeView As System.Windows.Forms.TreeView
 43     Private m_TopNode As Integer
 44     Private m_HierarchyCollecton As List(Of HierarchyMemberClass)
 45     Private m_DBConnectionString As String
 46     Private m_DBSelectCommandString As String
 47 
 48 
 49     Public Property TreeView() As System.Windows.Forms.TreeView
 50         Get
 51             Return m_TreeView
 52         End Get
 53         Set(ByVal value As System.Windows.Forms.TreeView)
 54             m_TreeView = value
 55         End Set
 56     End Property
 57     Public Property HierarchyCollecton() As List(Of HierarchyMemberClass)
 58         Get
 59             Return m_HierarchyCollecton
 60         End Get
 61         Set(ByVal value As List(Of HierarchyMemberClass))
 62             m_HierarchyCollecton = value
 63         End Set
 64     End Property
 65     Public Property TopNode() As Integer
 66         Get
 67             Return m_TopNode
 68         End Get
 69         Set(ByVal value As Integer)
 70             m_TopNode = value
 71         End Set
 72     End Property
 73     Public Property DBConnectionString() As String
 74         Get
 75             Return m_DBConnectionString
 76         End Get
 77         Set(ByVal value As String)
 78             m_DBConnectionString = value
 79         End Set
 80     End Property
 81     Public Property DBSelectCommandString() As String
 82         Get
 83             Return m_DBSelectCommandString
 84         End Get
 85         Set(ByVal value As String)
 86             m_DBSelectCommandString = value
 87         End Set
 88     End Property
 89 
 90     Public Sub New(ByVal TreeView As System.Windows.Forms.TreeView, _
 91                    ByVal DBConnectionString As String, _
 92                    ByVal DBSelectCommandString As String)
 93         m_TreeView = TreeView
 94         m_DBConnectionString = DBConnectionString
 95         m_DBSelectCommandString = DBSelectCommandString
 96         m_TopNode = -1
 97         m_HierarchyCollecton = HierarchyCollecton
 98     End Sub
 99 
100 
101     Public Sub FillTree()
102         Dim HierarchyCollecton As New List(Of HierarchyMemberClass)
103 
104         TreeView.BeginUpdate()
105         Call FillListFromDb(HierarchyCollecton)
106         Call RecurTree(TreeView, Nothing, TopNode, HierarchyCollecton)
107         TreeView.EndUpdate()
108         'tree.ExpandAll() 334173
109     End Sub
110     Private Sub RecurTree(ByVal TreeView As System.Windows.Forms.TreeView, _
111                           ByVal parentNode As System.Windows.Forms.TreeNode, _
112                           ByVal TopNode As Integer, _
113                           ByVal HierarchyCollecton As List(Of HierarchyMemberClass))
114         For intTemp As Integer = 0 To HierarchyCollecton.Count - 1
115             If HierarchyCollecton.Item(intTemp).ParentMemberID = TopNode Then
116                 Dim tmpNode As New System.Windows.Forms.TreeNode(HierarchyCollecton.Item(intTemp).MemberName)
117                 RecurTree(TreeView, tmpNode, HierarchyCollecton.Item(intTemp).MemberID, HierarchyCollecton)
118                 If parentNode Is Nothing Then
119                     TreeView.Nodes.Add(tmpNode)
120                 Else
121                     parentNode.Nodes.Add(tmpNode)
122                 End If
123             End If
124         Next
125     End Sub
126 
127     Private Sub FillListFromDb(ByVal HierarchyCollecton As List(Of HierarchyMemberClass))
128         Dim HierarchyMember As HierarchyMemberClass
129         Dim cnnDBase As New System.Data.SqlClient.SqlConnection
130         Dim cmdSQL As New System.Data.SqlClient.SqlCommand
131         Dim rdrTree As System.Data.SqlClient.SqlDataReader
132 
133         cnnDBase.ConnectionString = DBConnectionString '
134         cnnDBase.Open()
135 
136         cmdSQL.Connection = cnnDBase
137         cmdSQL.CommandText = DBSelectCommandString '
138 
139         rdrTree = cmdSQL.ExecuteReader
140         Do While rdrTree.Read
141             HierarchyMember = New HierarchyMemberClass(CInt(rdrTree(0)), CInt(rdrTree(1)), rdrTree(2).ToString)
142             HierarchyCollecton.Add(HierarchyMember)
143         Loop
144         rdrTree.Close()
145         cnnDBase.Close()
146     End Sub
147 
148     Public Function GetNodeRelationship(ByVal nodNodeOld As System.Windows.Forms.TreeNode, ByVal nodNodeNew As System.Windows.Forms.TreeNode) _
149                                         As Integer
150         If nodNodeOld Is nodNodeNew Then
151             Return 0
152         ElseIf nodNodeOld.FullPath.Length > nodNodeNew.FullPath.Length Then
153             ' if the two nodes belong to the same subtree, then nodNodeOld is a (grand)child of nodNodeNew
154             If nodNodeOld.FullPath.IndexOf(nodNodeNew.FullPath) = 0 Then
155                 ' do the loop only if the two nodes appear to belong to the same
156                 ' subtree check that the relationship really exists
157                 Do Until (nodNodeOld.Parent Is Nothing)
158                     nodNodeOld = nodNodeOld.Parent
159                     GetNodeRelationship = GetNodeRelationship - 1
160                     If nodNodeOld Is nodNodeNew Then Exit Function
161                 Loop
162             End If
163         Else
164             ' if the two nodes belong to the same subtree, then nodNodeOld is a (grand)parent of nodNodeNew
165             If nodNodeNew.FullPath.IndexOf(nodNodeOld.FullPath) = 0 Then
166                 ' do the loop only if the two nodes appear to belong to the same
167                 ' subtree check that the relationship really exists
168                 Do Until (nodNodeNew.Parent Is Nothing)
169                     nodNodeNew = nodNodeNew.Parent
170                     GetNodeRelationship = GetNodeRelationship + 1
171                     If nodNodeOld Is nodNodeNew Then Exit Function
172                 Loop
173             End If
174         End If
175         ' Nodes belong to different subtrees
176         Return 999999999
177     End Function
178 End Class
179 
180 
181 ' Пример использования класса
182 
183 Imports TopName.CoolTreeClass
184 
185     Private FillHierarchyTree As FillHierarchyTreeClass
186 
187     Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
188 
189         Dim strConnection As String = "Data Source=ServerNam;Initial Catalog=DBName;Integrated Security=True"
190         Dim strSql As String = "SELECT DivisionID, DivisionTopID, DivisionName FROM Seller.Division Order BY DivisionName"
191         FillHierarchyTree = New FillHierarchyTreeClass(Me.treeViewControl, strConnection, strSql)
192     End Sub
193 
194 
195     Private Sub cmdFill_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdFillAll.Click
196         Me.treeViewControl.Nodes.Clear()
197         FillHierarchyTree.TopNode = -1
198         FillHierarchyTree.FillTree()
199         Me.treeViewControl.ExpandAll()
200     End Sub
201 
202 'Кроме того, метод класса 
203 intRelation = FillHierarchyTree.GetNodeRelationship(FirstNode,SecondNode)
204 
205 позволяет определить отношение между Node дерева
206 
207 intRelation = 0   ' FirstNode есть SecondNode
208 
209 intRelation = -n  ' FirstNode есть потомок SecondNode n-ого уровня
210 
211 intRelation = n   ' FirstNode есть предок SecondNode n-ого уровня
212 
213 intRelation = 9999999  ' FirstNode и SecondNode не имеют общих предков
Вернуться к списку исходников в категории ADO.NET
 
Apartments for Rent

Rambler's Top100
Рейтинг@Mail.ru
Идея: Dimon aka Manowar Программирование: Dimon aka Manowar Дизайн: Dan Lebedev
Хостинг от компании Parking.ru
Карта сайта