How would I use an Open File Dialog to select an Image and then put that Image in a Picturebox on another Form? - vb.net

How would I use an Open File Dialog to select an Image and then put that Image in a Picturebox Control on another Form?
Private Sub btnLogo_Click(sender As Object, e As EventArgs) Handles btnLogo.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:"
OpenFileDialog1.ShowDialog()
photo = OpenFileDialog1.FileName.ToString
I'm guessing this is wrong but I'm lost to what to do here.
Then once I have selected an Image; what would be the appropriate Code to put that Image into a Picturebox Control on the other Form ?

If I understood you correctly then it is pretty easy:
Sub OpenAnImageInPicturebox(ByRef pb As PictureBox)
Dim ofd As New OpenFileDialog
ofd.Filter = "Bitmap|*.bmp|JPEG|*.jpg" 'If you like file type filters you can add them here
'any other modifications to the dialog
If ofd.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub
Try
Dim bmp As New Bitmap(ofd.FileName)
If Not IsNothing(pb.Image) Then pb.Image.Dispose() 'Optional if you want to destroy the previously loaded image
pb.Image = bmp
Catch
MsgBox("Not a valid image file.")
End Try
End Sub

try this:
photo = image.Fromfile( OpenFileDialog1.FileName)
Hope it helps

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please select a file"
OpenFileDialog1.InitialDirectory = "c:"
OpenFileDialog1.ShowDialog()
PictureBox1.ImageLocation = OpenFileDialog1.FileName.ToString
PictureBox1.Visible = True
End Sub

I came across this question when I was looking for Filter, as an update to previous answers.
You want to use OpenFileDialog to select an Image to put in a PictureBox Control in another Form. I suggest :-
Use Module : to use the Image on any Form
Use Default Image : to display in PictureBox Control whenever Error occurred. Use Project Resources to add Existing Resource (I.E. PNG Image file : noPhotoUsr).
Code for Module1
Module Module1
Public Function _GetImgOFD(Frm As Form, PicBx As PictureBox) As Bitmap
Dim _ErrBitmap As Bitmap = My.Resources.noPhotoUsr
Dim ChosenBitmap As Bitmap
Using OFD As OpenFileDialog = New OpenFileDialog
With OFD
.Filter = ("Image File (*.ico;*.jpg;*.bmp;*.gif;*.png)|*.jpg;*.bmp;*.gif;*.png;*.ico")
.RestoreDirectory = True
.Multiselect = False
.CheckFileExists = True
If .ShowDialog(Frm) = DialogResult.OK Then
ChosenBitmap = Bitmap.FromFile(.FileName)
Else
ChosenBitmap = _ErrBitmap
End If
End With
End Using
Return ChosenBitmap
End Function
End Module
Code to use in any Form, PictureBox Click Event
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
PictureBox1.Image = Module1._GetImgOFD(Me, PictureBox1)
End Sub

Related

is it possible to open image and then add it in the resources?

this is my code
Private Sub open_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles open_btn.Click
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.Load(OpenFileDialog1.FileName)
End If
if the image is opened, is it possible to add that image in the resources at the same time?
please help me.
Yes, it is possible to do so, but they will not be a part of your application afterward, if that is the expectation. Instead, your application will be dependent on an external resources file.
Dim result As DialogResult = openFileDialog1.ShowDialog()
If result = DialogResult.OK Then
Dim bitmap As New Bitmap(openFileDialog1.FileName)
Dim writer = New ResourceWriter("my.resources")
writer.AddResource("myImage", bitmap)
writer.Close()
End If
Some reference:
How to use Resources.resx dynamically i,e add new items dynamically
https://msdn.microsoft.com/en-us/library/stf461k5(v=vs.110).aspx

selecting controls from flowlayoutpanel in vb.net2008

i m using flowlayout panel to dynimacally create pictureboxes on the widows form. My actual problem is that, i want to see specific image in picturebox when user clicks on the item in flow layout panel using click event..
I hade tried some code, but everytime i failed..please help.please suggest me my missing code with some details so i can understand it very well.
My code is -------------------------------------------------------
Private Sub Button9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button9.Click
' Style Explorer - Thubnail Viewer
' FlowLayoutPanel1.SuspendLayout()
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" + "All files (*.*)|*.*"
OpenFileDialog1.Multiselect = True
OpenFileDialog1.Title = "Select Photos"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
For Each file As String In OpenFileDialog1.FileNames
Dim imageControl As New PictureBox()
imageControl.Name = "pic" & i.ToString()
imageControl.Height = 100
imageControl.Width = 100
Dim myCallback As New Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)
Dim myBitmap As New Bitmap(file)
Dim myThumbnail As Image = myBitmap.GetThumbnailImage(96, 96, myCallback, IntPtr.Zero)
imageControl.Image = myThumbnail
FlowLayoutPanel1.Controls.Add(imageControl)
Next
End If
End Sub
Public Function ThumbnailCallback() As Boolean
Return False
End Function
Inside the loop that add the pictureboxes to the FlowLayoutPanel you could add the name of the file to the Tag property of the dinamically created PictureBox and add an event handler for the click event
For Each file As String In OpenFileDialog1.FileNames
Dim imageControl As New PictureBox()
imageControl.Name = "pic" & i.ToString()
imageControl.Height = 100
imageControl.Width = 100
' Save the file from which you create the thumbnail
imageControl.Tag = file
' Set an event handler for the clickevent on the thumbnail
AddHandler imageControl.Click, AddressOf picClicked
.....
Next
Now write the event handler that responds to the click event
Private Sub picClicked(sender As Object, e As EventArgs)
Dim pic = DirectCast(sender, System.Windows.Forms.Control)
' The name of the file is in the Tag property....
Console.WriteLine(pic.Tag.ToString())
' Now its your job to display the image knowing the filename
End Sub

Is there a way in VB.NET to have buttons and menu bars that are built in the code show up in the design view?

Is there a way in VB.NET to make components like buttons and menus bars show in design view of you added them in programmatically?
I now in Java i you add a button in the code it will show in design view if you switch back and forth. Can this be done in VB.NET.
Code:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")
'adding the menu items to the main menu bar
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
' defining some sub menus
Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")
'add sub menus to the File menu
myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)
'add the main menu to the form
Me.Menu = mnuBar
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
'create a new TreeView
Dim TreeView1 As TreeView
TreeView1 = New TreeView()
TreeView1.Location = New Point(5, 30)
TreeView1.Size = New Size(150, 150)
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
'Creating the root node
Dim root = New TreeNode("Application")
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
'Creating child nodes under the first child
For loopindex As Integer = 1 To 4
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _
TreeNode("Sub Project" & Str(loopindex)))
Next loopindex
' creating child nodes under the root
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))
'creating child nodes under the created child node
For loopindex As Integer = 1 To 3
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _
TreeNode("Project File" & Str(loopindex)))
Next loopindex
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub openInWeb()
Try
Dim url As String = "http://www.stackoverflow.com"
Process.Start(url)
Catch ex As Exception
MsgBox("There's something wrong!")
Finally
End Try
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\Users\itpr13266\Desktop\Asnreiu3.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
openInWeb()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim myStream As Stream = Nothing
Dim openFileBox As New OpenFileDialog()
openFileBox.InitialDirectory = "c:\"
openFileBox.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileBox.FilterIndex = 2
openFileBox.RestoreDirectory = True
If openFileBox.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileBox.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
'**************************
' your code will go here *
'**************************
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
Private Sub ToolTip1_Popup(sender As System.Object, e As System.Windows.Forms.PopupEventArgs) Handles ToolTip1.Popup
End Sub
Private Sub Button(p1 As Object)
Throw New NotImplementedException
End Sub
Private Function myButton() As Windows.Forms.Button
Throw New NotImplementedException
End Function
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
AboutBox1.Show()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim lbl As New Label
lbl.Size = New System.Drawing.Size(159, 23) 'set your size (if required)
lbl.Location = New System.Drawing.Point(12, 190) 'set your location
lbl.Text = "You just clicked button 5" 'set the text for your label
Me.Controls.Add(lbl) 'add your new control to your forms control collection
End Sub
Public Sub HellowWorld()
MsgBox("Hello World!")
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
HellowWorld()
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
Dim ProgressBar1 As ProgressBar
Dim ProgressBar2 As ProgressBar
ProgressBar1 = New ProgressBar()
ProgressBar2 = New ProgressBar()
'set position
ProgressBar1.Location = New Point(10, 200)
ProgressBar2.Location = New Point(10, 250)
'set values
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
ProgressBar1.Value = 130
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Value = 40
'add the progress bar to the form
Me.Controls.Add(ProgressBar1)
Me.Controls.Add(ProgressBar2)
' Set the caption bar text of the form.
End Sub
End Class
The Designer does only show Controls that are created in the FormName.Designer.vb file. It does not run code in the FormName.vb file. When adding controls in the Designer, they are added to the InitializeComponent() method in the FormName.Designer.vb file.
So the only way to show the controls in the Designer is to add them in the Designer or to edit the FormName.Designer.vb file manually. If you decide for the latter, you should mimic the code that is generated by the Designer very closely in order to avoid problems when the Designer is shown. Also, be prepared that the Designer regards the FormName.Designer.vb file as completely generated code and might decide to recreate the file sooner or later omitting parts that it cannot handle.
Side note: in order to see the FormName.Designer.vb file, you should select "Show All Files" for the project in Solution Explorer.

Save Data to text tile using SaveFileDialog?

I have already viewed the MSDN Example but I am still having problems.
I created a super-simple program to multiply two numbers, and display the output in the textbox. Now I need to be able to read that text box value and put the value in a text file, bringing up the save to file dialog when the "Save To File" button is clicked.
Private Sub MutiplyBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MutiplyBtn.Click
Dim FirstNum As Double = Num1.Text
Dim SecondNum As Double = Num2.Text
Dim Answer2 As Double = FirstNum * SecondNum
Answerbox.Text = Answer2
End Sub
Private Sub SaveResultToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveResultToFile.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
System.IO.File.WriteAllText(Answerbox.Text)
myStream.Close()
End If
End If
End Sub
Currently, Visual Studio is giving me an error: Overload resolution failed because no accessible 'WriteAllText' accepts this number of arguments.
WriteAllText static method requires the name of the file where the data should be written to.
You could use directly the name selected in the saveFileDialog1
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
System.IO.File.WriteAllText(saveFiledialog1.FileName, Answerbox.Text)
End If
instead if you really want to use the stream opened by OpenFile() method your code should be
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim sw As StreamWriter = new StreamWriter(saveFileDialog1.OpenFile())
If (sw IsNot Nothing) Then
sw.WriteLine(Answerbox.Text)
sw.Close()
End If
End If
The code is an example, you need to add a bit of error handling
Hi I tried above method but I succeed in this way....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, RichTextBox1.Text, True)
End If
End Sub

How to op-en file and view in a rich text box using vb.net?

Hi I am trying to open and view a files text in a rich text box. Here is what I have please let me know what I am doing wrong?
Private Sub loadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadButton.Click
' Displays an OpenFileDialog so the user can select a Cursor.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Cursor Files|*.txt"
openFileDialog1.Title = "Select a Cursor File"
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
' Assign the cursor in the Stream to the Form's Cursor property.
Me.mainRTBox = New Text(openFileDialog1.OpenFile())
End If
End Sub
The problem you were having was that you weren't reading the file at all, and you weren't assigning the content of the file to the RichTextBox correctly.
Specifically, this code you have:
Me.mainRTBox = New Text(openFileDialog1.OpenFile())
.. should be:
Me.mainRTBox.Text = FileIO.FileSystem.ReadAllText(openFileDialog1.FileName)
This code will work:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Displays an OpenFileDialog so the user can select a Cursor.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Cursor Files|*.cur"
openFileDialog1.Title = "Select a Cursor File"
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
' Assign the cursor in the Stream to the Form's Cursor property.
Dim extension = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("."))
If extension Is "cur" Then
Me.mainRTBox.Text = FileIO.FileSystem.ReadAllText(openFileDialog1.FileName)
End If
End If
End Sub
End Class
Edit: I updated the code so that it checks if the user did actually open a Cur (cursor) file.
RichTextBoxes have a built in function for viewing RTF files and TXT files.
Code for a RTF file:
RichTextBox1.LoadFile("YOUR DIRECTORY", RichTextBoxStreamType.RichText)
Code for a TXT file:
RichTextBox1.LoadFile("YOUR DIRECTORY", RichTextBoxStreamType.PlainText)
Hope it helps
-nfell2009