none
Saving filename to listbox RRS feed

  • Question

  • I am creating a program that saves,loads and prints a text file. I have a textbox that can load a text file. I need help showing the file name of the text file opened in the textbox to appear on the listbox. 
    Tuesday, April 17, 2018 3:11 PM

Answers

  • The below code merely centers the Form on the Screen at runtime if the Form is not launched maximized.

    The error should only occur if the ListBox has no filenames present or for some reason the filespaths index is invalid. You left out two lines of code I provided. One clears the ListBox and one clears the filespaths list of string. That could be the reason you are having problems. See bottom code and compare it to the code you display.

    Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
    

    See the two lines in below code "ListBox1.Items.Clear" and "filesPaths.Clear". These clear the ListBox and filesPaths list of string so you don't constantly just add to both of them because at 65535 lines the ListBox would fail much less the time to load it over a huge amount of file names would be massive. And the indexes could become out of sync at some point between the ListBox and filePaths list(Of String).

       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using OFD As New OpenFileDialog
                With OFD
                    .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
                    .Multiselect = True
                    .Filter = "Text files (*.Txt)|*.Txt"
                    .Title = "Get text files"
                End With
                If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                    ListBox1.Items.Clear()
                    filesPaths.Clear()
                    For Each Item In OFD.FileNames
                        filesPaths.Add(Item)
                        ListBox1.Items.Add(IO.Path.GetFileNameWithoutExtension(Item))
                    Next
                End If
            End Using
        End Sub
    



    La vida loca

    • Marked as answer by Chintan1226 Tuesday, May 1, 2018 2:43 PM
    • Unmarked as answer by Chintan1226 Tuesday, May 1, 2018 2:44 PM
    • Marked as answer by Chintan1226 Thursday, May 3, 2018 11:45 AM
    Thursday, April 26, 2018 6:27 PM

All replies

  • Hi

    Don't do anything sensible like showing us the code you have so far!


    Regards Les, Livingston, Scotland

    Tuesday, April 17, 2018 3:40 PM
  • How do you get the filename to load a TextBox with? However you get the filename then use  ListBox1.Items.Add(Filename).

    La vida loca

    Tuesday, April 17, 2018 3:58 PM
  • I am creating a program that saves,loads and prints a text file. I have a textbox that can load a text file. I need help showing the file name of the text file opened in the textbox to appear on the listbox. 

    Hi Chintan1226,

    You just want to add text file name that loading in the textbox in ListBox, here is example that do this:

    Dim filename As String = "D:\Testfile\Test4.txt"
            TextBox1.Text = My.Computer.FileSystem.ReadAllText(filename)
            ListBox1.Items.Add(filename)

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, April 18, 2018 2:30 AM
    Moderator
  • Thank you for your response. This is what I have currently and all it does is opens a file dialog and adds the file name to the listbox. However, it does not show what the txt file is containing on the textbox. I was wondering what I could add to the code to have the txt file show the words on the textbox. 

     Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                Next
            Else
                'Do if user Cancel/Close Dialog
    
            End If
    
        End Sub



    • Edited by Chintan1226 Thursday, April 19, 2018 3:45 PM
    Thursday, April 19, 2018 3:02 PM
  •     Dim directory As String
        Dim listFileExtensions As List(Of String)
        Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                listFileExtensions = New List(Of String)
                directory = System.IO.Path.GetDirectoryName(arrayname(0))
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                    listFileExtensions.Add(System.IO.Path.GetExtension(MyFile))
                Next
            Else
            End If
        End Sub
    
        Private Sub lstFileNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstFileNames.SelectedIndexChanged
            TextBox1.Text = System.IO.File.ReadAllText(directory + "\" + lstFileNames.SelectedItem + listFileExtensions.Item(lstFileNames.SelectedIndex))
        End Sub


    Thursday, April 19, 2018 6:01 PM
  • Thank you for your response. This is what I have currently and all it does is opens a file dialog and adds the file name to the listbox. However, it does not show what the txt file is containing on the textbox. I was wondering what I could add to the code to have the txt file show the words on the textbox. 

     Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                Next
            Else
                'Do if user Cancel/Close Dialog
    
            End If
    
        End Sub



    Well this uses a List(Of String) also as Vikram Manjare's code does. However it clears the ListBox and the List(Of String) if the result is OK for the Open File Dialog. That way the ListBox is empty, as well the List(Of String), when new files names or paths are added to the ListBox and List(Of String).

    All of the files I tested with (File1 to File20) contain the same text followed by the File Number the file is associated to.

    Option Strict On
    
    Public Class Form1
    
        Dim filesPaths As New List(Of String)
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using OFD As New OpenFileDialog
                With OFD
                    .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
                    .Multiselect = True
                    .Filter = "Text files (*.Txt)|*.Txt"
                    .Title = "Get text files"
                End With
                If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                    ListBox1.Items.Clear()
                    filesPaths.Clear()
                    For Each Item In OFD.FileNames
                        filesPaths.Add(Item)
                        ListBox1.Items.Add(IO.Path.GetFileNameWithoutExtension(Item))
                    Next
                End If
            End Using
        End Sub
    
    
        Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
            TextBox1.Text = My.Computer.FileSystem.ReadAllText(filesPaths(ListBox1.SelectedIndex))
        End Sub
    
    End Class


    La vida loca

    Sunday, April 22, 2018 9:03 PM
  • I used the code you provided above however it does not show the content written in a text document. It just shows a blank textbox.
     Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                listFileExtensions = New List(Of String)
                directory = System.IO.Path.GetDirectoryName(arrayname(0))
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                    listFileExtensions.Add(System.IO.Path.GetExtension(MyFile))
                Next
            Else
            End If
    
        End Sub
    
    Private Sub lstFileNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstFileNames.SelectedIndexChanged
            txtDrop.Text = System.IO.File.ReadAllText(Directory + "\" + lstFileNames.SelectedItem + listFileExtensions.Item(lstFileNames.SelectedIndex))
        End Sub



    • Edited by Chintan1226 Tuesday, April 24, 2018 3:13 PM
    Tuesday, April 24, 2018 2:49 PM
  • Thank you for your response. This is what I have currently and all it does is opens a file dialog and adds the file name to the listbox. However, it does not show what the txt file is containing on the textbox. I was wondering what I could add to the code to have the txt file show the words on the textbox. 

     Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                Next
            Else
                'Do if user Cancel/Close Dialog
    
            End If
    
        End Sub



    No it does not, it adds all the filenames which are selected in the openfiledialog to your listbox without an extension.

    Why don't you simply use the first reply from mr. Monkeyboy,  

    Or does Cherry know something you did only tell here?

     

    Success
    Cor

    Tuesday, April 24, 2018 4:16 PM
  • Here is a possible way to go, basically doing the same thing as currently replies but with classes.

    Public Class FileItem
        Public Property FullName As String
        Public ReadOnly Property FileName As String
            Get
                Return IO.Path.GetFileName(FullName)
            End Get
        End Property
        Public ReadOnly Property Path As String
            Get
                Return IO.Path.GetDirectoryName(FullName)
            End Get
        End Property
        Public Overrides Function ToString() As String
            Return FileName
        End Function
    End Class

    .

    ''' <summary>
    ''' No assertion or exception handling, add as you see fit
    ''' </summary>
    Public Class FileOperations
        Public Function CreateItemList(pFiles As String()) As List(Of FileItem)
            Return pFiles.Select(Function(file) New FileItem With {.FullName = file}).ToList
        End Function
        Public Function Read(pFile As String) As String()
            Return IO.File.ReadAllLines(pFile)
        End Function
        Public Sub Update(pfile As String, pLines As String())
            IO.File.WriteAllLines(pfile, pLines)
        End Sub
    End Class

    .

    Public Class Form1
        Protected ops As New FileOperations
        Private WithEvents pd As New Printing.PrintDocument
        Private ppd As PrintPreviewDialog
        Private Sub cmdLoad_Click(sender As Object, e As EventArgs) Handles cmdLoad.Click
            '
            ' Bypassing use of a dialog as the important thing is working with an
            ' array of files.
            '
            ListBox1.DataSource = ops.
                CreateItemList(IO.Directory.GetFiles("C:\OED\Dotnetland\TextFiles"))
    
        End Sub
    
        Private Sub ListBox1_SelectedIndexChanged(
            sender As Object, e As EventArgs) _
            Handles ListBox1.SelectedIndexChanged
    
            If ListBox1.DataSource IsNot Nothing Then
                TextBox1.Lines = ops.Read(CType(ListBox1.SelectedItem, FileItem).FullName)
            End If
    
        End Sub
    
        Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
            If ListBox1.DataSource IsNot Nothing Then
    
                If My.Dialogs.Question($"Update {ListBox1.Text}") Then
                    ops.Update(CType(ListBox1.SelectedItem, FileItem).FullName, TextBox1.Lines)
                End If
            End If
    
        End Sub
    
        Private Sub cmdPrint_Click(sender As Object, e As EventArgs) Handles cmdPrint.Click
            'http://www.vbforums.com/showthread.php?548579-A-beginner-s-guide-to-printing-in-NET
        End Sub
    End Class
    
    UI, SplitContainer with a ListBox and TextBox.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, April 24, 2018 4:51 PM
    Moderator
  • I used the code you provided above however it does not show the content written in a text document. It just shows a blank textbox.
     Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                listFileExtensions = New List(Of String)
                directory = System.IO.Path.GetDirectoryName(arrayname(0))
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                    listFileExtensions.Add(System.IO.Path.GetExtension(MyFile))
                Next
            Else
            End If
    
        End Sub
    
    Private Sub lstFileNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstFileNames.SelectedIndexChanged
            txtDrop.Text = System.IO.File.ReadAllText(Directory + "\" + lstFileNames.SelectedItem + listFileExtensions.Item(lstFileNames.SelectedIndex))
        End Sub




        Dim DirectoryPath As String
        Dim listFileExtensions As List(Of String)
        Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
            If Me.OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim arrayname() As String = OpenFileDialog1.FileNames
                listFileExtensions = New List(Of String)
                DirectoryPath = System.IO.Path.GetDirectoryName(arrayname(0))
                lstFileNames.Items.Clear()
                txtDrop.Clear()
                For Each MyFile As String In arrayname
                    lstFileNames.Items.Add(System.IO.Path.GetFileNameWithoutExtension(MyFile))
                    listFileExtensions.Add(System.IO.Path.GetExtension(MyFile))
                Next
            End If
        End Sub
    
        Private Sub lstFileNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstFileNames.SelectedIndexChanged
            If lstFileNames.SelectedIndex >= 0 Then
                txtDrop.Text = System.IO.File.ReadAllText(DirectoryPath + "\" + lstFileNames.SelectedItem + listFileExtensions.Item(lstFileNames.SelectedIndex))
            End If
        End Sub
    


    Tuesday, April 24, 2018 5:12 PM
  • Option Strict is on however my code for a drag and drop feature gets messed up. This is my entire code for the project. Also randomly I still get this error. Also what is the relevance of this code that is giving me the error? In addition, " Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2))) " What is this code trying to accomplish?
    Imports System.IO
    Public Class UsingFiles1
    
    
        Dim strName As String                       'String to hold input Box Name
        Dim intCount1 As Integer                    'Counter Variable
        Dim FileWriter As StreamWriter              'Holds the object variable Open the file and write the data
        Dim results As DialogResult                 'Holds the result from opening a dialog box
        Dim filesPaths As New List(Of String)       'Holds the files for a lsitbox (of string specifies it to be a string)
    
        Private Sub txtDrop_DragDrop(sender As Object, e As DragEventArgs) Handles txtDrop.DragDrop
            If e.Data.GetDataPresent(DataFormats.FileDrop) Then
                Dim MyFiles() As String
                ' Assign the files to an array.
                MyFiles = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
                ' Display the file Name
                ' TextBoxDrop.Text = MyFiles(0)
                ' Display the file contents
                txtDrop.Text = My.Computer.FileSystem.ReadAllText(MyFiles(0))
            End If
        End Sub
    
        Private Sub txtDrop_DragEnter(sender As Object, e As DragEventArgs) Handles txtDrop.DragEnter
            If e.Data.GetDataPresent(DataFormats.FileDrop) Then
                e.Effect = DragDropEffects.All
            End If
        End Sub
    
        Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
            results = SaveFileDialog1.ShowDialog
    
            'Saves the file anywhere you want and any extension you want
            If results = DialogResult.OK Then
                FileWriter = New StreamWriter(SaveFileDialog1.FileName, True)
                FileWriter.Write(txtDrop.Text)
                FileWriter.Close()
            End If
    
    
        End Sub
        Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
    
            Using OFD As New OpenFileDialog
                With OFD
                    .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
                    .Multiselect = True
                    .Filter = "Text files (*.txt)|*.txt"
                    .Title = "Get text files"
                End With
                If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                    For Each Item In OFD.FileNames
                        filesPaths.Add(Item)
                        lstFileNames.Items.Add(IO.Path.GetFileNameWithoutExtension(Item))
                    Next
                End If
            End Using
    
        End Sub
        Private Sub ResetToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResetToolStripMenuItem.Click
            'Clears the textbox and listbox
            txtDrop.Text = String.Empty
            lstFileNames.Items.Clear()
        End Sub
        Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
            'Closes the Application
            Me.Close()
        End Sub
    
        Private Sub UsingFiles1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'Shows the date and time
            lblDT.Text = Now.ToString("D") & " " & Now.ToString("T")
    
            Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
        End Sub
    
        Private Sub lstFileNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstFileNames.SelectedIndexChanged
            txtDrop.Text = My.Computer.FileSystem.ReadAllText(filesPaths(lstFileNames.SelectedIndex))
    
        End Sub
    
        Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
            Dim OBJ As New Form1
            'Transfer the data from txtDrop to form 2
            OBJ.StringPass = txtDrop.Text
            OBJ.Show()
            Me.Hide()
        End Sub
    End Class







    • Edited by Chintan1226 Thursday, April 26, 2018 3:24 PM
    Thursday, April 26, 2018 2:56 PM
  • The below code merely centers the Form on the Screen at runtime if the Form is not launched maximized.

    The error should only occur if the ListBox has no filenames present or for some reason the filespaths index is invalid. You left out two lines of code I provided. One clears the ListBox and one clears the filespaths list of string. That could be the reason you are having problems. See bottom code and compare it to the code you display.

    Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
    

    See the two lines in below code "ListBox1.Items.Clear" and "filesPaths.Clear". These clear the ListBox and filesPaths list of string so you don't constantly just add to both of them because at 65535 lines the ListBox would fail much less the time to load it over a huge amount of file names would be massive. And the indexes could become out of sync at some point between the ListBox and filePaths list(Of String).

       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using OFD As New OpenFileDialog
                With OFD
                    .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
                    .Multiselect = True
                    .Filter = "Text files (*.Txt)|*.Txt"
                    .Title = "Get text files"
                End With
                If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                    ListBox1.Items.Clear()
                    filesPaths.Clear()
                    For Each Item In OFD.FileNames
                        filesPaths.Add(Item)
                        ListBox1.Items.Add(IO.Path.GetFileNameWithoutExtension(Item))
                    Next
                End If
            End Using
        End Sub
    



    La vida loca

    • Marked as answer by Chintan1226 Tuesday, May 1, 2018 2:43 PM
    • Unmarked as answer by Chintan1226 Tuesday, May 1, 2018 2:44 PM
    • Marked as answer by Chintan1226 Thursday, May 3, 2018 11:45 AM
    Thursday, April 26, 2018 6:27 PM