JLM JLM - 5 months ago 74
Vb.net Question

Open file from a listbox

I'm trying to open files from a

listbox
, the files could be Word, PDF, Excel, etc. Does there need to be separate code for each file type, or is there some way to just open the file when its double clicked?

The
listbox
populates fine through the use of the update
button
I have.

Public Class frmMain

Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
Dim folderInfo As New IO.DirectoryInfo("my directory is here")
Dim arrFilesInFolder() As IO.FileInfo
Dim fileInFolder As IO.FileInfo
arrFilesInFolder = folderInfo.GetFiles("*.*")
For Each fileInFolder In arrFilesInFolder
ListBox1.Items.Add(fileInFolder.Name)
Next
End Sub

Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
Me.Close()
End Sub

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick

End Sub

End Class

Answer

In its simplest form you just need to pass the filename to the Process.Start method

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
   Dim fullPath = Path.Combine("YourDirectoryHere", ListBox1.SelectedItem.ToString())
   System.Diagnostics.Process.Start(fullPath)
End Sub

However, this requires that you have saved the directory and recombine it with your file name.

Another problem is the file type (extension) that you try to open. The method that fills the listbox use *.* to load the FileInfo. So every kind of file is added to the listbox and this could be a problem if there is no program associated with that extension.

See more info on Process.Start(string) here