Search code examples
vb.netwinformscomboboxlistboxselection

How do I select a file in OpenFileDialog using Combo Box Selected item?


OPENFILEDIALOG - SELECT FILE FROM COMBOBOX

Hi everyone! I've been searching for a solution, but I'm drawing a blank? I'm using Win Forms, VS 2019, Win10, VB.NET.

What I Need

  1. I am populating a Combo Box with the File Names from a folder; 2. Clicking an item in the Combo uses OpenFileDialog to select a file which populates a ListBox with lines from the text file which corresponds with the selected item in the Combo. This is all working!

What I want to do is: When the user clicks an item in the Combo Box I want the Open File Dialog to open with the file already selected that corresponds to the item clicked in the Combo Box.

Code I Am Using

I'm using the following code in the SelectedIndexChanged event of the Combo Box to use the Open File Dialog to open the default folder where the user can select a file to populate the listbox with:

Dim openfile = New OpenFileDialog() With {.Filter = "Text (*.Text)|*.txt"}

    With openfile
        .InitialDirectory = "C:\Users\" + "username" + "\Documents\WIN32 VIEWER"
    End With

    If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then

        For Each line As String In File.ReadAllLines(openfile.FileName)
            ListBox1.Items.Add(line)
        Next
    End If

What I have tried

I have successfully used the following code in another program to select the corresponding file in Open File Dialog. But, I'm not sure how to adapt this code to the "Code I am using" example above? I tried, but couldn't find a way to apply the "/select" command to my example code? Maybe there's a different way of doing this? If anyone can give an example or point me to an example of how to achieve this I would greatly appreciate it!

Dim sFileName As String = ofd.FileName  (Original code uses: "C:\Images\Test.png")
    Process.Start("explorer.exe", "/select," & sFileName)

Solution

  • A few suggestions:

    • You can build a class (here, named DisplayFile) that is initialized with a File (full path), which then exposes properties and methods useful in your context:
      • Returns a Title for the file (here, the File name without extension)
      • The File name and Path
      • A public method (GetLines()) that returns the content of the File as an array of strings
      • Overrides ToString() to return the Title property value
    Friend NotInheritable Class DisplayFile
        Public Sub New(pathOfFile As String)
            FilePath = pathOfFile
            FileName = Path.GetFileName(pathOfFile)
            Title = Path.GetFileNameWithoutExtension(pathOfFile)
        End Sub
        Public ReadOnly Property FileName As String
        Public ReadOnly Property FilePath As String
        Public ReadOnly Property Title As String
    
        Public Function GetLines() As String()
            Return File.ReadAllLines(FilePath)
        End Function
    
        Public Overrides Function ToString() As String
            Return Title
        End Function
    End Class
    

    In your Form, initialize a List of this class objects from Directory.Getfiles().
    With this collection, initialize the DataSource of a ComboBox. Since the DisplayMember is not set, each Item displays the result of [object].ToString(): in this case, [DisplayFile].ToString() returns the Title property value (which represents the File name without extension)

    Imports System.IO
    
    Public Class SomeForm
        Private displayFiles As List(Of DisplayFile) = Nothing
    
        Public Sub New()
            InitializeComponent()
    
            Dim filesPath = Path.Combine(Environment.GetFolderPath(
                Environment.SpecialFolder.MyDocuments), "WIN32 VIEWER")
            displayFiles = Directory.GetFiles(filesPath, "*.txt").Select(Function(f) New DisplayFile(f)).ToList()
            cboFilesList.DataSource = displayFiles
            cboFilesList.SelectedIndex = -1
        End Sub
    End Class
    

    Since each Item of the ComboBox is a DisplayFile object, you cast [ComboBox]SelectedItem to DisplayFile and call its GetLines() method to fill a ListBox Control with the content of the File:

    subscribe to the SelectionChangeCommitted event of your ComboBox

    ' [...]
    Private Sub someComboBox_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles someComboBox.SelectionChangeCommitted
        someListBox.Items.Clear()
        someListBox.Items.AddRange(CType(someComboBox.SelectedItem, DisplayFile).GetLines())
    End Sub
    ' [...]