I am populating a treeview with a list of music. The root node's text is "Library". I want to go to a specific artist by typing the name. If I want to go to "Billy Idol", for example, when I type "Billy" it goes to the first Billy in the list, but when I press space and "I", the treeview will jump to the first "I" in the tree. How can I change this behavior?
I expect the treeview to select Billy Idol, instead of jumping to the first "I".
The text file uses tabs to show level of the Treeview item.
Migrating the code from VB6 due to it's lack of Unicode support. In VB6, catch the space chacter in KeyDown event and change KeyCode to 0. I can't find anyway to do this in VB.net.
Here is the code:
Imports System.IO
Public Class Form1
Inherits System.Windows.Forms.Form
Dim mNode As TreeNode
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim file_name As String = Application.StartupPath
file_name = file_name.Substring(0, file_name.Length - 1)
file_name = file_name.Substring(0, file_name.LastIndexOf("\"))
file_name &= "\test.txt"
LoadTreeViewFromFile(file_name, TreeView1)
TreeView1.Sort()
End Sub
Private Sub LoadTreeViewFromFile(ByVal file_name As String, ByVal trv As TreeView)
Dim stream_reader As New StreamReader(file_name)
Dim file_contents As String = stream_reader.ReadToEnd()
stream_reader.Close()
file_contents = file_contents.Replace(vbLf, "")
Const charCR As Char = CChar(vbCr)
Const charTab As Char = CChar(vbTab)
Dim lines() As String = file_contents.Split(charCR)
Dim text_line As String
Dim level As Integer
Dim tree_nodes() As TreeNode
Dim num_nodes As Integer = 0
ReDim tree_nodes(num_nodes)
trv.Nodes.Clear()
For i As Integer = 0 To lines.GetUpperBound(0)
text_line = lines(i)
If text_line.Trim().Length > 0 Then
level = text_line.Length - text_line.TrimStart(charTab).Length
If level > num_nodes Then
num_nodes = level
ReDim Preserve tree_nodes(num_nodes)
End If
If level = 0 Then
tree_nodes(level) = trv.Nodes.Add(text_line.Trim())
Else
tree_nodes(level) = tree_nodes(level - 1).Nodes.Add(text_line.Trim())
If level = 1 Then tree_nodes(level).EnsureVisible()
End If
End If
Next i
If trv.Nodes.Count > 0 Then trv.Nodes(0).EnsureVisible()
End Sub
Private Sub TreeView1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TreeView1.KeyPress
If TreeView1.SelectedNode.Parent Is TreeView1.Nodes(0) Then TreeView1.SelectedNode.Expand()
End Sub
End Class