Show Text Files Content in Textbox using Listbox

Wilfred Eghenedji 326 Reputation points
2022-04-10T16:55:24.877+00:00

What am trying to do is, "I want Listbox2 to be populated with all the .txt files in Startuppath (each file being a line), and when i select each file in the Listbox, the selected file content should open in a textbox". The following code aims to:

  1. Populate listbox2 with .txt files in StartupPath
  2. Enable the whole content of selected file/entry show in textbox Public Sub New()
    InitializeComponent()
    Dim dir = New DirectoryInfo(Application.StartupPath)
    For Each file In dir.GetFiles("*.txt")
    ListBox2.Items.Add(file)
    Next
    ListBox2.DisplayMember = "Name"
    End Sub Private Sub listBox2_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim fileName As String = (CType(ListBox2.SelectedItem, FileInfo)).FullName
    If File.Exists(fileName) Then
    TxtNotePad.Text = File.ReadAllText(fileName)
    End If
    ListBox2.Visible = False
    End Sub THE PROBLEM

After implementing the foregoing code, the Listbox was populated accordingly, but when I selected an entry, the textbox shows nothing, appearing empty. What could have gone wrong? Would appreciate any solution to this. Thank you.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,568 questions
0 comments No comments
{count} votes

Accepted answer
  1. LesHay 7,126 Reputation points
    2022-04-10T17:16:32.523+00:00

    Hi

    Here is an example to do the same. I suggest you trace your own code to see what/why it isn't working as you expect. Are you familiar with using BreakPoints etc?

    This is a stand alone example. The Form1 only has ListBox1 and TextBox1 (multiline) on it.

    Option Strict On
    Option Explicit On
    Public Class Form1
        ' these variable would likely be set from user
        ' selecting the folder with (say) a FolderBrowser
        ' but just hard coded here for this example
        Dim fold As String = My.Computer.FileSystem.SpecialDirectories.Desktop
        Dim files() As String = IO.Directory.GetFiles(fold, "*.txt")
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ListBox1.Items.AddRange(files)
        End Sub
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            Dim file As String = ListBox1.SelectedItem.ToString
            TextBox1.Text = IO.File.ReadAllText(file)
        End Sub
    End Class
    

0 additional answers

Sort by: Most helpful