VB.NET 2010 Passing Picture from OpenFile Dialog Box to another form - vb.net

I am creating a loan program that opens a Custom Form Dialog Box, you choose the picture, click open and then need to pass it to another form to use after hitting OK from the Dialog Box. This is my code when I click the Logo File button from my custom Dialog Form.
The Form is called Dialog Form and I need to send the picture to the NewLoanCaculatorForm to populate a picture area in the form.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogoFile.Click
Dim mystream As Stream = Nothing
'Open the File to pickup icon for Loan Calculator
Dim OpenFileDialog1 As New OpenFileDialog
'Set up and display the open File Dialog
With OpenFileDialog1
'Begin in the current Directory
.InitialDirectory = "C:\"
.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
End With
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
mystream = OpenFileDialog1.OpenFile()
If (mystream IsNot Nothing) Then
' I believe the coded goes here but I'm stuck
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (mystream IsNot Nothing) Then
mystream.Close()
End If
End Try
End If
End Sub

This is how I usually do things like this:
Create global variable in the DialogForm:
Public Property sPath as String
or
Public Property imgLogo as Image
To get the Image do this:
imgLogo = Image.FromFile(OpenFileDialog1.FileName)
Or simply do:
sPath = OpenFileDialog1.FileName
instead of
mystream = OpenFileDialog1.OpenFile()
Then when you have done this you close the form by clicking the OK button or whatever you call it.
Then in your main form NewLoanCaculatorForm where you call DialogForm you simply do:
img = DialogForm.imgLogo
or
path = DialogForm.sPath
img = Image.FromFile(path)
Depending on which way you stored the info in the DialogForm.
Also, if you are looking for images I would recommend you not to have .txt in your filter. That would seriously ruin the execution.

Related

How to WriteAllText but restrict to overwrite the existing file?

Jan 8. 2023:
The AppendAllText can append into existing file and can create a file if no file exist.
the WriteAllText can Write into new created file and overwrite the existing file.
I'm trying to find another alltext for what I want to happen.
What I want to do is to save my textboxcontent.text into txt file.
I want to save 3 different content that will be displayed into my textboxcontent.text
And I only have one button.
That one button will open savefiledialog but with the code I have, I can only do 2 things, Write and Append.
Now, This is what suppose to happen.
*If I save the textcontent.text to an existing txt file, it will prompt message box "Do you want to overwrite this file?" And even if I click Yes, it will not allow to.
I must be able to create new txt file since I was not able to overwrite the file.
The reason is because I don't want to delete or overwrite the existing file with important information saved in it.
I hope somebody can help me.
This is the code I have.
```Imports System.io
Private lastSaveFileName As String = String.Empty
Private Function GetSaveFileName3(ByVal suggestedName As String) As String
Using sfd3 As New SaveFileDialog()
sfd3.Filter = "Text Files (*.txt) |*.txt"
sfd3.FileName = suggestedName
sfd3.OverwritePrompt = True
If DialogResult.OK Then
End If
If sfd3.ShowDialog() = DialogResult.OK Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
Else
End If
Return String.Empty
End Using
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
lastSaveFileName = GetSaveFileName3(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.AppendAllText(lastSaveFileName, TextContent.Text)
End If
End Sub ' This code above includes IMPORTS.IO
Jan 9, 2023: Update
This is what I've done so far.
I tried to use the File.Exist but I don't know where to place it to make it run in the way I wanted.
Please see this code and help me fix it.
This code is running well in almost the way I want. I'm missing something.
Imports System.IO
Private lastSaveFileName As String = String.Empty
Private Sub SaveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveFile.Click
If Not File.Exists(lastSaveFileName) Then
lastSaveFileName = GetSaveFileName(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
End If
ElseIf File.Exists(lastSaveFileName) Then
lastSaveFileName = GetSaveFileName2(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
End If
End If
End Sub
Private Function GetSaveFileName2(ByVal suggestedName As String) As String
Using sfd As New SaveFileDialog()
sfd.Filter = "Text Files (*.txt) |*.txt"
sfd.FileName = suggestedName
sfd.OverwritePrompt = True
If sfd.ShowDialog() = DialogResult.OK Then
'If File.Exists(lastSaveFileName) Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
End If
Return String.Empty
End Using
End Function
Private Function GetSaveFileName(ByVal suggestedName As String) As String
Using sfd As New SaveFileDialog()
sfd.Filter = "Text Files (*.txt) |*.txt"
sfd.FileName = suggestedName
sfd.OverwritePrompt = True
If sfd.ShowDialog() = DialogResult.OK Then
Return sfd.FileName
End If
Return String.Empty
End Using
End Function
With this code, I was able to save the textdisplay to a txtfile but it's like, it's bypassing the Elseif function.
Sometimes, poeple forgot to avoid important files and accidentally deleted it. This is what I'm preventing to happen.
I let the overwriteprompt true to let it ask the user if they want to replace. It accidentally click the yes, this will show message "This file have records from your last session, Please create new file to save new records." means that even the user want to replace it, the program will not allow it. I don't want to remove that scenario.
(Scenario 1)
What happen in this code is this, when I click the button, savefiledialog pop up and giving me choice how I want to save the textdisplay.
I can create new file or replace existing file.
First, I choose to replace, and a messagebox shows and saying, I can't replace the file.
Then I create new file, it lets me save the txt display normally.
(scenario 2)
That's what I want. The code runs that way at first, but if you click the button again, and try to create new file first, the message box will show saying I can't replace the file. then when I choose to replace, no message box shows and the file was replace. I lost the file.
That's where I need help. I only want the Scenario 1.
Please try on your own I you don't get what I mean.
I tried this and this code works the way I want.
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
If File.Exists(saveFileDialog1.FileName) Then
MessageBox.Show("A file with that name already exists. Please select a different file name or choose a different location to save the file.")
Else
File.WriteAllText(saveFileDialog1.FileName, Txtdisplay1.Text)
End If
End If
End Sub
Answered by: schoemr

Saving listbox's file not just its name

Im working on my first injector in VB.NET.
Im trying to save the loaded dll in listbox, but it only saves the name.
I select the dll, inject, it saves my.settings, but once I reopen the injector it only saves the dll's name, not its path, so I have to browse and select it again
I was thinking about maybe I have to save openfiledialog or something but really got no clue
Inject button:
My.Settings.dll = New Specialized.StringCollection
My.Settings.dll.AddRange(dll.Items.Cast(Of String).ToArray)
My.Settings.Save()
My.Settings.process = SteamTextBox2.Text
My.Settings.Save()
On form load:
If My.Settings.dll IsNot Nothing Then dll.Items.AddRange(My.Settings.dll.Cast(Of String).ToArray)
The problem with this the injector only needs the dll's name without path
Dim ExeName As String = IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)
Private Sub Inject()
pszLibFileRemote = OpenFileDialog1.FileName
End Sub
OpenFileDialog1.Filter = "DLL (*.dll) |*.dll"
OpenFileDialog1.ShowDialog()
OpenFileDialog1.ToString()
If IO.File.Exists(OpenFileDialog1.FileName) Then
Dim TargetProcess As Process() = Diagnostics.Process.GetProcessesByName(SteamTextBox2.Text)
If TargetProcess.Length = 0 Then
...
Else
Call Inject()
I want it to load the actual selected file not just it's name
Nothing is functionally wrong with your code. I guess the problem is with how you load the paths into the listbox in the first place. Here is some code to do that.
Add a new button called LoadButton, then this code for the handler
Private Sub LoadButton_Click(sender As Object, e As EventArgs) Handles LoadButton.Click
Dim filenames As IEnumerable(Of String)
Using dialog As New OpenFileDialog
dialog.Filter = "Application extensions (*.dll)|*.dll|All files (*.*)|*.*"
dialog.Multiselect = True
Select Case dialog.ShowDialog()
Case DialogResult.OK
filenames = dialog.FileNames
Case Else
filenames = Nothing
End Select
End Using
filenames = filenames.Select(Function(fn) System.IO.Path.GetFileName(fn))
If filenames?.Any() Then dll.Items.AddRange(filenames.ToArray())
End Sub
This will put the full path into the listbox. Does this solve the problem?

SaveFileDialog.ShowDialog not showing on a form from .dll

I have a windows form that contains a SaveFileDialog as a component. This form is called from a library (.dll). When you click on btnExport you should see the save file dialog window.
My problem is that SaveFileDialog1.ShowDialog doesn't show any window to select the directory path.
This is my code:
Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
SaveFileDialog1.Filter = "XLS File|*.xls"
SaveFileDialog1.Title = "SaveFileDialog title"
Try
' this should open the dialog
If Me.SaveFileDialog1.ShowDialog() = DialogResult.OK Then
' Do something
Else
' This is a custom function to show messages
ShowCustomMessage("Error opening SaveFileDialog")
End If
Catch ex As Exception
' Show exception
End Try
End Sub
Your code works. You could try the following -
Try removing the Try-Catch-End Try as it could be hiding an error from you since you didn't implement anything to handle the Catch.
Try specifying the Owner object when calling ShowDialog() to ensure it is not going behind your main form.
Me.SaveFileDialog1.ShowDialog(Me) ...

Allowing multiple files to be processed through one module

I've created a program to modify security settings of a .pdf file.
This works fine for one file - but I want to allow editing multiple .pdf's with the touch of one button and am struggling to make it work.
I have pasted the code for my GUI below, "Modify_PDF" is the module that runs the pdf security modification code. Is it possible to run multiple files through this module from here?
Dim source_file As String = ""
''' Handles clicking of the 'Open file' button
Private Sub open_button_Click(sender As System.Object, e As System.EventArgs) Handles open_button.Click
Dim input As FileStream = Nothing
'Set filter to only allow compatible files
OpenFileDialog.Filter = "PDF documents (*.pdf)|*.pdf"
'Allow multiple files to be opened
OpenFileDialog.Multiselect = True
'open the file selection dialogue
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
input = OpenFileDialog.OpenFile()
Catch Ex As Exception
MsgBox("Error opening file: " & vbCrLf & Ex.Message)
Finally
'Check this again to ensure no exception on open.
If (input IsNot Nothing) Then
input.Close()
End If
End Try
If input IsNot Nothing Then
source_file = OpenFileDialog.FileName
If Modify_PDF.process_file(source_file, "") Then
PDF_name.Text = Path.GetFileName(OpenFileDialog.FileName)
input.Close()
modify_button.Enabled = Modify_PDF.process_file(source_file, "") 'Allow report to be created if processing succeeds
End If
End If
End If
End Sub
''' Handles clicking of the 'Modify PDF' button
Private Sub generate_button_Click(sender As System.Object, e As System.EventArgs) Handles modify_button.Click
Modify_PDF.modify_pdf(source_file, source_file, "")
End Sub
Try it like this:
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
For Each FileName as String in OpenFileDialog.FileNames
'Do something with the filename here
Next
Catch ...

Get image location using a drag and drop

I have a drag and drop event to get images into a picture box. I need to get the image location to string to store on my database. I can get the location if I use a OpenFileDialog, but if I use a drag and drop, I can't seem to get it. Here is my code:
Private Sub picCategoryImage_DragEnter(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragEnter
'Procedure to copy the dragged picture from the
'open window
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
'If the file explorer is open, copy the picture to the box
e.Effect = DragDropEffects.Copy
picCategoryImage.BorderStyle = BorderStyle.FixedSingle
TextBox1.Text = picCategoryImage.ImageLocation
Else
'otherwise, don't take action
e.Effect = DragDropEffects.None
btnDeleteImage.Visible = False
End If
End Sub
Private Sub picCategoryImage_DragDrop(sender As Object, e As DragEventArgs) Handles picCategoryImage.DragDrop
'Procedure to select the pictue and drag to picturebox
Dim picbox As PictureBox = CType(sender, PictureBox)
Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
If files.Length <> 0 Then
Try
picbox.Image = Image.FromFile(files(0))
btnDeleteImage.Visible = True
picbox.BorderStyle = BorderStyle.None
picCategoryImage.BringToFront()
btnDeleteImage.BringToFront()
Catch ex As Exception
MessageBox.Show("Image did not load")
End Try
End If
End Sub
As suggested by Plutonix, you're already using the file path so you've already got it. That's how Image.FromFile is able to create an Image from a file. If you mean that you need to be able to get the path later then you have two main choices:
Do as you're doing and store the path in a member variable for later use.
Instead of calling Image.FromFile and setting the Image of the PictureBox, just call the Load method of the PictureBox. You can then get the path from the ImageLocation property.
I would actually suggest using option 2 regardless, because it has the added advantage of not locking the file the way your current code does.