Friday, April 29, 2011

Read Text File in ListBox

Write the code bellow:



        ListBox1.Items.Clear()
        Dim dialog As New OpenFileDialog
        dialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        dialog.Filter = "Text files (*.txt)|*.txt"
        Dim result As DialogResult = dialog.ShowDialog
        Dim fileContent As String = Nothing
        Dim fileLines() As String


        If result = Windows.Forms.DialogResult.OK AndAlso dialog.FileName <> String.Empty Then
            Using sr As New System.IO.StreamReader(dialog.FileName)
                fileContent = sr.ReadToEnd
                sr.Close()
            End Using
        End If
        fileLines = fileContent.Split(Convert.ToChar(vbLf))


        For index As Integer = 0 To fileLines.GetUpperBound(0)
            ListBox1.Items.Add(fileLines(index))
        Next
    End Sub

1 comment:

  1. Could you make a version excluding that dialog, you know for a specified file?

    ReplyDelete

There was an error in this gadget