Open Excel Workbook from ComboBox (VB.NET) - vb.net

How to open an excel workbook from combobox?
I am using following code to populate combobox with excel filenames,
Dim files() As String
files = Directory.GetFiles("C:\Files\Folder", "*.xlsx", SearchOption.AllDirectories)
For Each FileName As String In files
ComboBox1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
But I do not have any idea about how to open the selected file.

Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Private Const TargetDir = "C:\Files\Folder"
Private FullFileList As List(Of String)
Private Sub ProcessFile(ByVal fn As String)
If Path.GetExtension(fn).ToLower = ".xlsx" Then
FullFileList.Add(fn)
ComboBox1.Items.Add(Path.GetFileName(fn))
End If
End Sub
Private Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
Dim fileName As String
For Each fileName In fileEntries
ProcessFile(fileName)
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FullFileList = New List(Of String)
ProcessDirectory(TargetDir)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then
Dim prc As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo(FullFileList(ComboBox1.SelectedIndex))
psi.UseShellExecute = True
psi.WindowStyle = ProcessWindowStyle.Normal
prc.StartInfo = psi
prc.Start()
End If
End Sub
End Class

You'll need to handle an event to react to the user's selection: either a change to the selection in the ComboBox or (better) a Button click. In your event handler you can retrieve the filename from the ComboBox:
string filename = ComboBox1.SelectedItem.ToString()
Once you have the filename, you can open the file, although how you do this will depend on what you want to do with it. This answer has some information on opening Excel files in VB.NET.

Try using
Process.start("excel "+ComboBox1.SelectedItem.ToString());
on buttonclick event

Related

Copy a File Using DragDrop VB.Net

What is wrong with my code? Getting a 'Process cannot access the file because it is being used by another process' error msg Is there a way around this. My google-fu was not giving me much luck. I was not able to Move or Copy, and I will take either.
Private Sub frmFiberTransMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub frmFiberTransMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim filePaths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
Call CopyFileDrop(filePaths)
End If
End Sub
Private Sub CopyFileDrop(filePaths As String())
For Each fileLoc As String In filePaths
Dim fileName As String = fileLoc
Dim fi As New IO.FileInfo(fileName)
File.Create(fileName)
Dim justFileName As String = fi.Name
Dim newPathName As String = gProgDir & "\" & justFileName
Directory.Move(fileLoc, newPathName)
Next fileLoc
End Sub
File.Create(fileName) returns an open handle and you're not closing it. It doesn't look like you need that line. –
#LarsTech 50 mins ago

How to Save Textboxt.Text as file name?

What's wrong with this code?
I need to add textbox13.text (the value of it is in number) as the file name and how can I add an option which checks if the file already exists if so show an option saying replace or cancel when I press my save button.
So far here is the code :
Dim i As Integer = 0
Dim filepath As String = IO.Path.Combine("D:\Logs", Textbox13.Text + i.ToString() + ".txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(TextBox13.Text)
sw.WriteLine(TextBox1.Text)
sw.WriteLine(TextBox2.Text)
sw.WriteLine(TextBox3.Text)
sw.WriteLine(TextBox4.Text)
sw.WriteLine(TextBox5.Text)
sw.WriteLine(TextBox7.Text)
sw.WriteLine(TextBox9.Text)
sw.WriteLine(TextBox10.Text)
sw.WriteLine(TextBox11.Text)
sw.WriteLine(TextBox12.Text)
This is from Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Form2.WriteTextBoxTextToLabel(TextBox1.Text)
Form2.WriteTextBoxTextToTextbox(TextBox1.Text)
End Sub
This is from form2
Public Sub WriteTextBoxTextToLabel(ByVal Txt As String)
lblPD.Text = Txt
End Sub
Public Sub WriteTextBoxTextToTextbox(ByVal Txt As String)
TextBox13.Text = Txt
End Sub
Private Sub TextBox13_TextChanged(sender As Object, e As EventArgs) Handles TextBox13.TextChanged
TextBox13.Text = lblPD.Text
End Sub
You can add the following logic before creating the StreamWriter:
if system.io.file.exists(filepath) then
' The file exists
else
' The file does not exist
end if

GetDirectory will not list all Directories

I have a form that allows you to click a button, which triggers an OpenFileDialog. From there, you are suppose to select a specific file within that folder, and then the program is supposed to go through from the folder you were in the the /subjects folder and list those directories.
At the moment, I have 3 directories within /subjects: english, mathematics, and cte.
My issue is that when the program is ran, it will only list the English directory in the combo-box, and will not list any of the others.
Private Sub btnDocumentChoice_Click(sender As Object, e As EventArgs) Handles btnDocumentChoice.Click
Dim ofd As New OpenFileDialog
Dim DirList As New ArrayList
If ofd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso ofd.FileName <> "" Then
strRootLocation = (Path.GetDirectoryName(ofd.FileName))
GetDirectories(strRootLocation + "/subject/", DirList)
'MessageBox.Show(Path.GetDirectoryName(ofd.FileName))
End If
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
strRootLocation = OpenFileDialog1.FileName
cmbSubject.Items.Add(strRootLocation)
End Sub
Sub GetDirectories(ByVal StartPath As String, ByRef DirectoryList As ArrayList)
Dim Dirs() As String = Directory.GetDirectories(StartPath)
DirectoryList.AddRange(Dirs)
For Each Dir As String In Dirs
GetDirectories(Dir, DirectoryList)
cmbSubject.Items.Add(Replace(Path.GetDirectoryName(Dir), strRootLocation + "\subject", ""))
cmbSubject.Items.Remove("")
Next
End Sub
I managed to fix my own issue by removing the For Each loop in the question, and replacing it with this:
Dim directories As String
For Each directories In Directory.GetDirectories(strRootLocation + "\subject")
cmbSubject.Items.Add(Replace(directories, strRootLocation + "\subject\", ""))
Next

Deleting Specific Files and then Extract them into another folder

With the following code I am trying to delete specific files inside of a folder on a flash drive, and then copy the remaining files into a separate folder. When the program runs and I initiate the button to do so, the program deletes files that have not been modified within the past year, but then it does not continue to extract the remaining files and place them into a separate folder.
Does anyone know why?
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
DeleteUnmodifiedFiles(sourceDirectory, 365)
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
Private Sub DeleteUnmodifiedFiles(ByVal directoryName As String, ByVal modificationThresholdDays As Integer)
Dim folder As New DirectoryInfo(directoryName)
Dim thresholdDate As Date
Dim wasModifiedSinceThreshold As Boolean
For Each file As FileInfo In folder.GetFiles
thresholdDate = DateTime.Now().AddDays(-1 * modificationThresholdDays)
wasModifiedSinceThreshold = (file.LastWriteTime > thresholdDate)
If (Not wasModifiedSinceThreshold) Then file.Delete()
Next
MessageBox.Show("Deleting Files")
End Sub
End Class
This will delete any file in the source directory that hasn't been modified for a year, and then will move any remaining files to the destination directory...
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim fileListA() As String
fileListA = (IO.Directory.GetFiles("C:\Scource_Directory"))
For Each i As String In fileListA
If (IO.File.GetLastWriteTime(i).ToShortDateString.Substring(6)) < (CType(DateTime.Now.Year.ToString, Integer) - 1) Then
IO.File.Delete(i)
End If
Next
Dim fileListB() As String
fileListB = (IO.Directory.GetFiles("C:\Scource_Directory"))
For Each i As String In fileListB
IO.File.Move(i, "Destination_Directory")
Next
End Sub

Listview items and saving them as .csv

I'm doing this project where I need to save the names of the items from a listview to a .csv
Imports System.IO
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim returnValue As String()
returnValue = Environment.GetCommandLineArgs()
If returnValue.Length > 1 Then
MessageBox.Show(returnValue(1).ToString())
Else
MessageBox.Show("Nothing")
End If
' Set ListView Properties
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
' Create Columns Headers
lstvicon.Columns.Add("Nome")
lstvicon.Columns.Add("Extensão")
lstvicon.Columns.Add("Tamanho")
lstvicon.Columns.Add("Data Modificação")
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.SubItems.Add(file.Extension)
li.SubItems.Add(file.Length)
li.SubItems.Add(file.LastWriteTimeUtc)
'li.SubItems.Add(FileDialog)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
' Creates a csv File
Dim csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
lstvicon.SelectedItems.CopyTo(csv)
csv.Close()
End Sub
End Class
That's what I got but I can't seem to get it to write on the .txt.
I have no idea where to go from here and i've been going around this for hours, so any help would be apreciated.
I think that you want something like this:
' Creates a csv File
Using csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
For Each oItem As ListViewItem In ListView1.Items
csv.WriteLine(String.Format("""{0}"",""{1}"",{2},{3}", oItem.Text, oItem.SubItems(0).Text, oItem.SubItems(1).Text, oItem.SubItems(2).Text )
Next
End Using
You will probably need to clean up the csv formatting, but this should give you an idea.