Need Help with TreeVIew Logic

I am trying to fill the TreeView with all of the folders in my outlook. The code below work to just 2 folders deep. I need to have it go probably 10 deep. I have looked at a bunch of examples but can't seem to grasp the logic.

Any Ideas or guidance you can offer would be appreciated.


Thanks


Steve

Imports Outlook = Microsoft.Office.Interop.Outlook

Imports olNamespace = Microsoft.Office.Interop.Outlook.NameSpace

Private Sub btnGetFolders_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetFolders.Click

Dim olApp As Outlook.Application

Dim MyNameSpace As Outlook.NameSpace

Dim CurrentFolder As Outlook.MAPIFolder

Dim olNewFolder As Outlook.MAPIFolder

Dim olChildFolder As Outlook.MAPIFolder

Dim tvRoot As TreeNode

Dim tvNode As TreeNode

olApp = CreateObject("Outlook.Application")

MyNameSpace = olApp.GetNamespace("MAPI")

CurrentFolder = MyNameSpace.PickFolder

olNewFolder = CurrentFolder

MessageBox.Show(olNewFolder.FolderPath)

For Each olNewFolder In CurrentFolder.Folders

'If (olNewFolder.DefaultItemType) = 6 Then

tvRoot = Me.TreeFolders.Nodes.Add(olNewFolder.Name)

For Each olChildFolder In olNewFolder.Folders

tvNode = tvRoot.Nodes.Add(olChildFolder.Name)

Next

'End If

Next

End Sub




Answer this question

Need Help with TreeVIew Logic

  • Room222

    You need to use recursion.

    one method is to loop through the first level of folders and get all children of each folder by calling a recursive sub.

    so as a simple example have a look at this code and see if you can follow it.You can see that getchildren keeps calling itself untill it cant find any more children. then it pops back up the stack and will do that for every 0 level folder. step through it to see if that makes it easier to understand.

    Hope this helps

    Mike Pooley

    Private Sub FillTree()

    'FillTree

    Dim Row As DataRow

    Dim num As Integer

    For Each Row In mDataTable.Rows

    num = Row("ParentID")

    If num = 0 Then

    Dim TreeN As New TreeNode

    TreeN.Text = Row("NodeText")

    TreeView.Nodes.Add(TreeN)

    TreeN.Name = Row("NodeID")

    getchildren(Row("NodeID"), TreeN)

    End If

    Next

    end sub

    Private Sub getchildren(ByVal ParentID As Integer, ByVal TheTreeNode As TreeNode)

    Dim Row As DataRow

    For Each Row In mDataTable.Rows

    If Row("ParentID") = ParentID Then

    Dim TreeN As New TreeNode

    TreeN.Text = Row("NodeText")

    TreeN.Name = Row("NodeID")

    TheTreeNode.Nodes.Add(TreeN)

    getchildren(Row("NodeID"), TreeN)

    End If

    Next

    End Sub



  • Need Help with TreeVIew Logic