Read the whole file into a string. Use Split to split the file into lines.
For each line, use Split to break the line into fields. Compare the fields in the line to those in the previous line to see where the lines first differ. Create new TreeView nodes for the fields after this point of first difference.
Store the most recently created node at each level of indentation in the tree_nodes array so you can use it as the parent of the next node below that level.
|
' Load a TreeView control from a CSV file.
Private Sub LoadTreeViewFromCsvFile(ByVal file_name As _
String, ByVal trv As TreeView)
Dim fnum As Integer
Dim file_contents As String
Dim lines As Variant
Dim old_line As Variant
Dim new_line As Variant
Dim i As Integer
Dim level As Integer
Dim different As Boolean
Dim tree_nodes() As Node
Dim max_node As Integer
' Load the file.
fnum = FreeFile
Open file_name For Input As fnum
file_contents = input$(LOF(fnum), fnum)
Close fnum
' Split the file into lines.
lines = Split(file_contents, vbCrLf)
' Process each line.
TreeView1.Nodes.Clear
max_node = -1
old_line = Split("", ",")
For i = 0 To UBound(lines) - 1
' Split the new line into fields.
new_line = Split(lines(i), ",")
' Make room for new nodes.
If UBound(new_line) > max_node Then
max_node = UBound(new_line)
ReDim Preserve tree_nodes(0 To max_node)
End If
' We have not found a difference yet.
different = False
' Compare the new line's fields
' to the previous line's fields.
For level = 0 To UBound(new_line)
' See if the old and new lines
' differ at this entry.
If level > UBound(old_line) Then
different = True
ElseIf new_line(level) <> old_line(level) Then
different = True
End If
If different Then
' The lines are different.
' Add a new node here.
If level = 0 Then
Set tree_nodes(level) = _
TreeView1.Nodes.Add(, , , _
new_line(level))
Else
Set tree_nodes(level) = _
TreeView1.Nodes.Add(tree_nodes(level _
- 1), tvwChild, , new_line(level))
tree_nodes(level).EnsureVisible
End If
End If
Next level
' Save the new line.
old_line = new_line
Next i
End Sub
|