How to read a text file in Listbox opened with OpenFileDialog - Visual Basic 2017

Hot

Friday, October 27, 2017

How to read a text file in Listbox opened with OpenFileDialog

Knowing how to read a text file in Listbox is essential part in Visual Basic 2017 programming.

In this post I will teach you how to do it by using OpenFileDialog.

First let create a text file with notepad with the following data.

Read a text file in ListBox

Now save the file somewhere on the local disk. I save it as a test file.txt on the Desktop.

Add a button in the form and title it Read text file; add a listbox too.

Above Public Class Form1 insert the following code

Imports System.IO

If you are complete beginner and you don't know how it looks like see on the picture bellow!

How to read a text file in Listbox opened with OpenFileDialog


In the button insert the following code to read the text file in Listbox.

        Dim OpenFileDialog1 As New OpenFileDialog
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"

        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Dim lines = File.ReadAllLines(OpenFileDialog1.FileName)
            ListBox1.Items.Clear()
            ListBox1.Items.AddRange(lines)
        End If


No comments:

Post a Comment