You're reusing the same connection across multiple queries. Don't do that. Instead, create the connection when it's required, and dispose of it as soon as you've finished with it. Wrap all disposable objects in a
Using
block to make sure they're always disposed of properly.
You should also move your connection string to your application's configuration file, so that you don't have to recompile your application when you deploy it.
Imports System.Configuration
Imports System.Data.OleDb
Public Class Form1
Private Shared Function CreateConnection() As OleDbConnection
Dim settings As ConnectionStringSettings = ConfigurationManager.ConnectionString("connectionString")
Return New OleDbConnection(settings.ConnectionString)
End Function
Private Shared Sub LoadTopLevels(ByVal list1 As List(Of String), ByVal list2 As Dictionary(Of String, List(Of String)))
Using con As OleDbConnection = CreateConnection()
Using cmd As New OleDbCommand("select ID,Levels from tbltoplevels", con)
con.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
Dim key As String = reader.Item(1).ToString()
list1.Add(key)
list2.Add(key, New List(Of String))
End While
End Using
End Using
End Using
End Sub
Private Shared Sub LoadGroupLevels(ByVal list2 As Dictionary(Of String, List(Of String)))
Using con As OleDbConnection = CreateConnection()
Using cmd As New OleDbCommand("select ID,Heading,Level from tblgrouplevel", con)
con.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
Dim key As String = reader.Item(1).ToString()
list2(key).Add(reader.Item(2).ToString())
End While
End Using
End Using
End Using
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim list1 As New List(Of String)
Dim list2 As New Dictionary(Of String, List(Of String))
LoadTopLevels(list1, list2)
LoadGroupLevels(list2)
For Each item In list1
Dim GrandfatherNOde As TreeNode = TreeView1.Nodes.Add(item)
For Each Str As String In list2(item)
Dim fatherNode As TreeNode = GrandfatherNOde.Nodes.Add(Str)
Next
Next
End Sub
End Class