Drag treeview named TreeView1, textbox named TextBox1,
button named Button1.

I m adding nodes programmatically. Select the node,Enter text in TextBox1 & then click on Button1 to add the node.

Mine code is doing this, I want that when the user add nodes it automatically sorts.

Suppose user selects All(node) that is added on form_load,enter 1 in textbox1, click on buuton1,node added.

Second time again user selects All,enter 3 in textbox1,click on button1, node added.

Now the user enters 2 in textbox,click on button,node added. I want that nodes are automatically sorted after adding.

I want

ALL
       1
       2
       3

Currently i m getting output

ALL
       1
       3
       2
Public Class Form2

    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TreeView1.Nodes.Add("All")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim tnNew As New TreeNode
        Dim tnSelected As TreeNode

        If Trim(TextBox1.Text) = "" Then
            MsgBox("Enter text in Textbox")
            Exit Sub
        End If
        tnSelected = TreeView1.SelectedNode
        If Not tnSelected Is Nothing Then
            tnNew = tnSelected.Nodes.Add(TextBox1.Text)
            tnNew.EnsureVisible()
            TreeView1.Refresh()
        End If

        TextBox1.Text = ""
        TextBox1.Focus()
        TreeView1.ExpandAll()
    End Sub
End Class

If you're only going to have 1 root node then I would go with a TreeView1.Sort() before TreeView1.ExpandAll().

If you have more than 1 root node, then the root nodes will be sorted as well so you may have to throw them into a list and sort the list then change their orders once the child nodes have been sorted.

Hope that helps!

~Stevoni

This article has been dead for over six months. Start a new discussion instead.