Download a selected file from my GridView using DoubleClick - vb.net

I am trying to download a file that I uploaded into my GridView. Each time I double click on the second document in the GridView, it opens the first uploaded document and saves it
Here is my code:
Private Sub dgDocuments_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
Handles dgDocuments.DoubleClick
LoadUploadedDocuments()
Try
Dim objTransactionDocument As Objects.TransactionsDocuments
If dgDocuments.CurrentRowIndex.Equals(-1) Then
Dim obj As Object = dgDocuments.Item(dgDocuments.CurrentRowIndex, 1)
objTransactionDocument = Managers.TransactionsDocuments.SelectTransactionsDocuments(Convert.ToInt32(obj))
End If
If Not objTransactionDocument Is Nothing Then
If objTransactionDocument.TransactionsDocumentsID = 1 Then
Dim saveFile As New SaveFileDialog
saveFile.FileName = objTransactionDocument.FileLocation.Substring(objTransactionDocument.FileLocation.LastIndexOf("\"))
saveFile.Title = "Download supporting document to transaction " + m_objTransaction.TransactionID.ToString()
If saveFile.ShowDialog() = DialogResult.OK Then
Dim saveDir As String = Path.GetDirectoryName(saveFile.FileName)
Dim name As String = objTransactionDocument.FileLocation.Substring(objTransactionDocument.FileLocation.LastIndexOf("\"))
Dim saveLocation As String = saveDir + name
System.IO.File.Copy(objTransactionDocument.FileLocation, saveLocation)
MessageBox.Show("Document saved successfully")
End If
End If
End If
Catch ex As Exception
MessageBox.Show("Document saved unsuccessfully " + ex.ToString())
End Try
End Sub
What am I doing wrong?

add / to saveDir as
saveDir+='/'

Related

Create folder in a specified location with strings

I´ve been working in a code that allow user to create a folder in a location specified with folder browser and name it with two text strings, but at this far, I've managed to create the folder on the default location.
How can I set the location with the folder browser and have the new folder name with these texts as default.
The code this far is.
For create folder button:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim snombrecarpeta As String
Dim sruta As Object
snombrecarpeta = "QUO " & (quo.Text) & "_" & (proy.Text)
sruta = ccliente()
My.Computer.FileSystem.CreateDirectory(snombrecarpeta)
MsgBox("Se ha creado la carpeta del proyecto")
End Sub
For search folder button:
Private Sub ccliente_Click(sender As Object, e As EventArgs) Handles ccliente.Click
Dim ccliente = New FolderBrowserDialog()
ccliente.SelectedPath = ("E:\Crear_carpetas\Crear_carpetas")
If DialogResult.OK = ccliente.ShowDialog() Then
End If
Thanks in forward.
And yes, I´m just starting in the vb world.
Creation of folder on Desktop, see Environment.GetFolderPath, and IO.Directory.CreateDirectory
Dim snombrecarpeta As String
Dim sruta As Object
snombrecarpeta = "QUO " & (quo.Text) & "_" & (proy.Text)
sruta = ccliente()
'
' e.g. create directory on Desktop
'
snombrecarpeta = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), snombrecarpeta)
Try
IO.Directory.CreateDirectory(snombrecarpeta)
MessageBox.Show("Se ha creado la carpeta del proyecto")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
edit:
'
' https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.folderbrowserdialog?view=net-5.0
'
Dim path As String = ""
Dim snombrecarpeta As String
snombrecarpeta = String.Format("QUO{0}_{1}", (quo.Text), (proy.Text))
Using fbd As New FolderBrowserDialog
fbd.RootFolder = Environment.SpecialFolder.Desktop
If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
path = IO.Path.Combine(fbd.SelectedPath, snombrecarpeta)
End If
End Using

Opening a file from List View?

This is my first question on the site and I am fairy new at how code works. I need to be able to open a file from a list view. I can get the file path to open up my file explorer, but can not get it to directly open the selected file. It gives me an error saying "System.ComponentModel.Win32Exception: 'The system cannot find the file specified" I've checked the file path from my file explorer and the path it pulls from and they both seem to match. Here is an example of what I've written.
Private Sub ListView1_Function(sender As Object, e As EventArgs) Handles ListView1.ItemSelectionChanged
If Not ListView1.SelectedItems.Item(0).Text = "" Then
For Each ListViewItemVar As ListViewItem In ListView1.Items
Dim filePath As String = $"C:\Users\{My.User.Name.Split("\").ElementAt(1)}\S & J Tube Inc\Files_Storage - Documents\Shipping Wizard\"
Dim selectedFile As String = ListViewItemVar.Text
If ListViewItemVar.Selected = True Then
If MessageBox.Show("You are about to open " & filePath & ". Are you sure?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
Process.Start(filePath + selectedFile)
ElseIf DialogResult.No Then
MsgBox("You decided not to open the file.")
End If
End If
Next
End If
End Sub
You have to use ListView1_ItemActivate
1.Create a project with Form with ListView1 and Label1 controls on it
2.Replace yourName in dirInfo with your name from Users\eee\Documents
And all the code you need is :
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'CreateHeadersAndFillListView
ListView1.View = View.Details
ListView1.Columns.Add("Filename")
ListView1.Columns.Add("Size")
ListView1.Columns.Add("Last accessed")
Dim dirInfo As New DirectoryInfo("C:\Users\yourName\Documents")
Dim fileInfo As FileInfo
Dim lvi As ListViewItem
Dim lvsi As ListViewItem.ListViewSubItem
For Each fileInfo In dirInfo.GetFiles("*.*")
lvi = New ListViewItem With {
.Text = fileInfo.Name,
.ImageIndex = 1,
.Tag = fileInfo.FullName
}
lvsi = New ListViewItem.ListViewSubItem With {
.Text = fileInfo.Length.ToString()
}
lvi.SubItems.Add(lvsi)
lvsi = New ListViewItem.ListViewSubItem With {
.Text = fileInfo.LastAccessTime.ToString()
}
lvi.SubItems.Add(lvsi)
ListView1.Items.Add(lvi)
Next
'after populating the list this will size columns to the width of column data
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
Label1.Text = "C:\Users\yourName\Documents" + Environment.NewLine + " (Double click to open file !)"
AddHandler ListView1.ItemActivate, AddressOf ListView1_ItemActivate
End Sub
Private Sub ListView1_ItemActivate(sender As Object, e As System.EventArgs)
Dim filename As String = ListView1.SelectedItems(0).Tag.ToString()
Try
Process.Start(filename)
Catch
Return
End Try
End Sub

How to limit photo viewer to only display image files in the array?

array of the picture
Dim PicsBMP As New List(Of PictureBox)
For i As Integer = 0 To similarImageNewList.Count - 1
Pics.Add(New PictureBox)
Pics(i).Tag = i
Pics(i).Image = Image.FromFile(similarImageNewList(i))
Pics(i).Top = 25
Pics(i).Left = (i * 250) + 20
Pics(i).Width = 200
Pics(i).Height = 200
Pics(i).BorderStyle = BorderStyle.FixedSingle
Pics(i).SizeMode = PictureBoxSizeMode.StretchImage
AddHandler Pics(i).MouseClick, AddressOf imageCapture_mouseDoubleClick
Panel1.Controls.Add(Pics(i))
Next
mousedoubleClick
Private Sub imageCapture_mouseDoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Pics As PictureBox = DirectCast(sender, PictureBox)
Dim selected As Integer = DirectCast(Pics.Tag, Integer)
Dim filename As String = similarImageNewList(selected)
Try
Process.Start(filename)
Catch ex As Exception
MessageBox.Show("Error opening image file.",
"Load Watch Image Error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
End Try
End Sub
array of the selected picture
Dim imagePathName As String = imageName(count).Substring(0, imageName(count).Length - 6)
Dim fileEntries As String() = Directory.GetFiles(getDirectory, imagePathName + "*.jpg")
Dim fileName As String
For Each fileName In fileEntries
If (System.IO.File.Exists(fileName)) Then
similarImageNewList.Add(fileName)
End If
Next
When the Process.Start(filename) is triggered, the windows photo viewer will be displaying all of the file images in the file.. I only want the photo viewer to be displaying the photos included in the similarImageNewList.(i) loop..

Reading .txt files using StreamReader

I am having an issue, I have a program I'm working on and I have to be able to read multiple .txt files one after the other to update a string array called words(). The main problem is the first file I upload goes into the files()string array, when I run my drag and drop event the array is full and won't let me upload second. how do I reset the files()array after it has been uploaded successfully.
sample code:
Dim words(7) As String
Dim i As Integer = 0
Public Sub frmMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
Dim word As String = ""
Try
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
MsgBox(path)
Dim sr As New StreamReader(path)
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
i = i + 1
Loop
Next
GetPower()
Catch ex As Exception
'MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub frmMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
I believe this is because you are not resetting i, which means that eventually i increments out of the range of your words() array which is only size 7, which by the way will also throw an error if one of those files has more than 7 lines.
For Each path In files
i = 0 'reset counter
MsgBox(path)
Dim sr As New StreamReader(path)
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
i = i + 1
Loop
Next

Print Preview not displaying file

I am working on a menu strip Print Preview event. i worked out the following procedure to view a pdf file located in the same path as my workbook.
Private WithEvents docPrint As New PrintDocument()
' Declare a string to hold the entire document contents.
Private documentContents As String
' Declare a variable to hold the portion of the document that
' is not printed.
Private stringToPrint As String
Private Sub ReadDocument()
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
Dim stream As New FileStream(docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
documentContents = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
stringToPrint = documentContents
End Sub
Private Sub prnPrvStripCustomRange_Click(sender As Object, e As EventArgs) Handles prnPrvStripCustomRanges.Click
ReadDocument()
prnPrvCustomRanges.Document = docPrint
prnPrvCustomRanges.ShowDialog()
End Sub
The dialog pops up on click, but my document page is blank. I have another event for printing and that one prints the same document. So I don't understand what I am doing wrong on my preview.
Here is my print procedure:
Private Sub prnCustonPages_Click(sender As Object, e As EventArgs) Handles prnCustonPages.Click
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
prnPrtCustomRanges.Document = docPrint
prnPrtCustomRanges.PrinterSettings = docPrint.PrinterSettings
prnPrtCustomRanges.AllowSomePages = True
If prnPrtCustomRanges.ShowDialog = DialogResult.OK Then
docPrint.PrinterSettings = prnPrtCustomRanges.PrinterSettings
docPrint.Print()
End If
End Sub