Creating Tree View - All the points I have left

Hi All I have appreciated your help in the past.

I am using Visual Studio Net 2005 in VB to do web development.

I am trying to create a tree view to show all the folder on a specific drive, but I keep getting errors. This is a Sub I am tring to use I found on the net. It is called from a dropdownlist box when a drive is selected. Then should added all the folder to the tree. But I get the error -

Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.TreeNode'.

Protected Sub cbDrives_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbDrives.SelectedIndexChanged
        Dim SubDirs As String()

        ' Clear the treeview control
        TreeView1.Nodes.Clear()

        SubDirs = GetDirectories(cbDrives.Text)

        Dim x As Short
        Dim objNode As TreeNode

        objNode = New TreeNode(SubDirs(x)).Tag = cbDrives.Text & SubDirs(x) & "\"
       
        For x = 0 To SubDirs.Length - 2
            TreeView1.Nodes.Add(SubDirs(x)).Tag = cbDrives.Text & SubDirs(x) & "\"
        Next
    End Sub
MaritimerAsked:
Who is Participating?
 
Bob LearnedConnect With a Mentor Commented:
Partial Class TreeViewExample
  Inherits System.Web.UI.Page

  Protected Sub cbDrives_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbDrives.SelectedIndexChanged

    LoadTreeView(cbDrives.SelectedItem.Text)

  End Sub

  Private Sub LoadTreeView(ByVal initialDirectory As String)

    treeContents.Nodes.Clear()

    ' Create rootNode and add to TreeNode
    Dim rootNode As New TreeNode(initialDirectory)
    treeContents.Nodes.Add(rootNode)

    ' Load remaining Nodes
    LoadNode(rootNode, rootNode.Text)

    rootNode.Expand()

  End Sub


  Private Sub LoadNode(ByVal node As TreeNode, ByVal directory As String)

    'Validate the node passed in
    If node Is Nothing Then
      Throw New ArgumentNullException("The TreeNode is null.  Please create a new instance.")
      Exit Sub
    End If

    'Validate path passed in
    If My.Computer.FileSystem.DirectoryExists(directory) = False Then
      Throw New ArgumentException("Initial Directory does not exist.  Please enter a valid " & _
            "directory." & vbCrLf & vbCrLf & "Directory entered:  " & directory)

      Exit Sub

    End If

    Dim nod As TreeNode = Nothing

    Dim di As New System.IO.DirectoryInfo(directory)
    For Each dir As IO.DirectoryInfo In di.GetDirectories()
      nod = New TreeNode(dir.Name)

      Try
        For Each subDir As IO.DirectoryInfo In dir.GetDirectories()
          LoadNode(nod, subDir.FullName)

        Next

      Catch ex As Exception
      End Try

      node.ChildNodes.Add(nod)

    Next

  End Sub

End Class

Bpb
0
 
Bob LearnedCommented:
What line are you getting that exception on?

I would try something like this:

Protected Sub cbDrives_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbDrives.SelectedIndexChanged
       
        ' Clear the treeview control
        TreeView1.Nodes.Clear()

        Dim SubDirs As String() = GetDirectories(cbDrives.Text)

        For x As Integer = 0 To SubDirs.Length - 2
           Dim objNode As New TreeNode(SubDirs(x))
           objNode.Tag = cbDrives.Text & SubDirs(x) & "\"
       
            TreeView1.Nodes.Add(objNode)
        Next
    End Sub

Bob
0
 
VBRocksCommented:
Here's an example of how you can do this:

        Public Sub LoadTreeView(ByRef treeView As TreeView, _
            ByVal initialDirectory As String)

            'Validate TreeView passed in
            If treeView Is Nothing Then
                Throw New ArgumentNullException("The TreeView is null.  Please create a new instance.")
                Exit Sub

            End If


            treeView.Nodes.Clear()

            'Create rootNode and add to TreeNode
            Dim rootNode As New TreeNode(initialDirectory)
            treeView.Nodes.Add(rootNode)

            'Load remaining Nodes
            LoadNode(rootNode, rootNode.Text)

            rootNode.Expand()

        End Sub


        Public Sub LoadNode(ByRef node As TreeNode, ByVal directory As String)

            'Validate the node passed in
            If node Is Nothing Then
                Throw New ArgumentNullException("The TreeNode is null.  Please create a new instance.")
                Exit Sub
            End If

            'Validate path passed in
            If My.Computer.FileSystem.DirectoryExists(directory) = False Then
                Throw New ArgumentException("Initial Directory does not exist.  Please enter a valid " & _
                      "directory." & vbCrLf & vbCrLf & "Directory entered:  " & directory)

                Exit Sub

            End If

            Dim nod As TreeNode = Nothing

            Dim di As New System.IO.DirectoryInfo(directory)
            For Each dir As IO.DirectoryInfo In di.GetDirectories()
                nod = New TreeNode(dir.Name)

                Try
                    For Each subDir As IO.DirectoryInfo In dir.GetDirectories()
                        LoadNode(nod, subDir.FullName)

                    Next

                Catch ex As Exception
                End Try

                node.Nodes.Add(nod)

            Next

        End Sub

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
MaritimerAuthor Commented:
I havent tried eithere solution yet (I will right now) but I was getting my error.
on

 TreeView1.Nodes.Add(objNode)
0
 
MaritimerAuthor Commented:
Hi Bob I am getting the same error on your suggestion.
I will try yours next VBRocks
0
 
MaritimerAuthor Commented:
Hi VBRocks

I have tried yours, your logic seems to work. But I have two problems. My tere seems to be invisible. The name of the tree on the webpage is Treeview1

Protected Sub cbDrives_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbDrives.SelectedIndexChanged
              Dim treeview As New TreeView
        LoadTreeView(treeview, "C:\")
        treeview1.Visible = True
    End Sub
0
 
VBRocksCommented:
Well, I have to confess that I am a Windows guy, and not much of a Web guy.  But do you have to add it to the Controls collection first?

For example, in Windows, you have to add it to the Controls collection before you can see it:
        Dim treeview As New TreeView()
        LoadTreeView(treeview, "C:\")

        'Add to Controls collection
        Me.Controls.Add(treeview)

        treeview.Visible = True

0
 
MaritimerAuthor Commented:
No I don't think so I tried that an get the error.

Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.TreeNode'.

VB Net is a bit different. I was able to do this in VB. With net there seems to be a learning curve.


0
 
Bob LearnedCommented:
Can you show us what you have now?

Bob
0
 
MaritimerAuthor Commented:
Here is my code. I am currently using. It is from VBRocks.

Protected Sub cbDrives_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbDrives.SelectedIndexChanged
       
        Dim treeview As New TreeView
       
        LoadTreeView(treeview, "C:\")
        treeview.Visible = True

    End Sub


Public Sub LoadTreeView(ByRef treeView As TreeView, _
            ByVal initialDirectory As String)

        'Validate TreeView passed in
        If treeView Is Nothing Then
            Throw New ArgumentNullException("The TreeView is null.  Please create a new instance.")
            Exit Sub

        End If


        treeView.Nodes.Clear()

        'Create rootNode and add to TreeNode
        Dim rootNode As New TreeNode(initialDirectory)
        treeView.Nodes.Add(rootNode)

        'Load remaining Nodes
        LoadNode(rootNode, rootNode.Text)

        rootNode.Expand()

    End Sub


    Public Sub LoadNode(ByRef node As TreeNode, ByVal directory As String)

        'Validate the node passed in
        If node Is Nothing Then
            Throw New ArgumentNullException("The TreeNode is null.  Please create a new instance.")
            Exit Sub
        End If

        'Validate path passed in
        If My.Computer.FileSystem.DirectoryExists(directory) = False Then
            Throw New ArgumentException("Initial Directory does not exist.  Please enter a valid " & _
                  "directory." & vbCrLf & vbCrLf & "Directory entered:  " & directory)

            Exit Sub

        End If

        Dim nod As TreeNode = Nothing

        Dim di As New System.IO.DirectoryInfo(directory)
        For Each dir As IO.DirectoryInfo In di.GetDirectories()
            nod = New TreeNode(dir.Name)

            Try
                For Each subDir As IO.DirectoryInfo In dir.GetDirectories()
                    LoadNode(nod, subDir.FullName)

                Next

            Catch ex As Exception
            End Try

            node.Nodes.Add(nod)

        Next

    End Sub
0
 
MaritimerAuthor Commented:
This is what I was using.

Both should work. But I cant seem to figure out what I am doing wrong.

I get the error:

Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.TreeNode'.
on:
 TreeView1.Nodes.Add(SubDirs(x)).Tag = cbDrives.Text & SubDirs(x) & "\"
I have dropped and dragged a tree on my webpage. ad a ddl to select the drive letter

on

Protected Sub cbDrives_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbDrives.SelectedIndexChanged
        Dim SubDirs As String()

        '' Clear the treeview control
        TreeView1.Nodes.Clear()

        SubDirs = GetDirectories(cbDrives.Text)
       
        Dim x As Short
        Dim objNode As TreeNode

        objNode = New TreeNode(SubDirs(x)).Tag = cbDrives.Text & SubDirs(x) & "\"

        For x = 0 To SubDirs.Length - 2
            TreeView1.Nodes.Add(SubDirs(x)).Tag = cbDrives.Text & SubDirs(x) & "\"
           
        Next
       

    End Sub



Function GetDirectories(ByVal Path As String, Optional ByVal Filter As String = "*.*") As String()
       

        Dim DirInfo As New DirectoryInfo(Path)
        Dim Di As DirectoryInfo
        Dim i As Short
        Dim TempDir() As String

        i = 0

        For Each Di In DirInfo.GetDirectories() '(Filter)
            ReDim Preserve TempDir(i + 1)
            TempDir(i) = Di.Name
            i = i + 1
        Next

        GetDirectories = TempDir

        Exit Function


    End Function
0
 
Bob LearnedCommented:
Try this:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="TreeViewExample.aspx.vb" Inherits="TreeViewExample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>TreeView Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:DropDownList ID="cbDrives" runat="server" AutoPostBack="True">
            <asp:ListItem>D:</asp:ListItem>
            <asp:ListItem>C:</asp:ListItem>
        </asp:DropDownList>
        <asp:TreeView ID="treeContents" runat="server">
        </asp:TreeView>
    </form>
</body>
</html>
0
 
MaritimerAuthor Commented:
Hi TheLearnedOne
I must be missing something else I still get the same error, this time on: TreeView1.Nodes.Add(rootNode)
I assume that TreeContents is the ID of the Tree so I changed it to TreeView1
Maybe I am missing an include or something

Private Sub LoadTreeView(ByVal initialDirectory As String)

        TreeView1.Nodes.Clear()

        ' Create rootNode and add to TreeNode
        Dim rootNode As New TreeNode(initialDirectory)
        TreeView1.Nodes.Add(rootNode) '---------Value of type 'System.Windows.Forms.TreeNode' cannot be converted to 'System.Web.UI.WebControls.TreeNode'

        ' Load remaining Nodes
        LoadNode(rootNode, rootNode.Text)

        rootNode.Expand()

    End Sub
0
 
Bob LearnedCommented:
1) I have 2005 SP1

2) I worked up that example, and it ran without error.

3) I don't understand why you are getting that error.

4) Can you try to recreate a test page from the HTML page, and the code-behind that I showed, and see if you still get that error?

Bob
0
 
MaritimerAuthor Commented:
I also have 2005 SP 1

I am creating this as a ASP.net web using VB as the language.

Your right it does work, when I created a new app. I wonder if my old one is corrupt or something I will try rebooting.

Wierd I would get that same error over and over agin in my project. Maybe my first attempt was correct.
0
 
MaritimerAuthor Commented:
Thanks Bob I found the problem it was due to this import that I had by accident.

One last thing would you no what this error represents.

When I click on a nod this happans

Microsoft JScript runtime error: 'TreeContents_Data' is undefined.
0
 
Bob LearnedCommented:
treeContents is the name of the control in that example page that I showed you.

Bob
0
 
MaritimerAuthor Commented:
OK Bob

Thanks for your help.

Also thanks for the help in the past.
0
 
Bob LearnedCommented:
I think you owe something to VBRocks also.

Bob
0
 
MaritimerAuthor Commented:
Oh Sorry

I already awarded the points I will ask the Moderator if there is anyway we could still split the points.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.