How to load picture into Flowlayoutpanel without Openfiledialog - vb.net

I am still unable to find this solutions, could you please help me that would be great for me. Actually I want to load picture into Flowlayoutpanel without Openfiledialog, whenever I want to run the application it automatically load picture from given file path.
Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
Dim TheFilePath As String
Dim F as string = System.IO.Directory.GetFiles(Application.StartupPath + "C:\Users\Mohammed Waseem\Pictures\", "*.jpg")
Dim fbd As New FolderBrowserDialog
If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
TheFilePath = fbd.SelectedPath
Try
For Each F As String In System.IO.Directory.GetFiles(fbd.SelectedPath)
Dim NewImage As Image = Image.FromFile(F)
NewImage = NewImage.GetThumbnailImage(NewImage.Width * 0.5, NewImage.Height * 0.5, AddressOf abort, System.IntPtr.Zero)
Dim P As New PictureBox
P.SizeMode = PictureBoxSizeMode.AutoSize
P.Image = NewImage
AddHandler P.Click, AddressOf PictureBox1_Click
FlowLayoutPanel1.Controls.Add(P)
ListBox1.Items.Add(System.IO.Path.GetFileName(F))
Next
Catch ex As Exception
End Try
End If
End Sub
Private Function abort() As Boolean
Return False
End Function
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Dim strFileName As String = DirectCast(sender, PictureBox).Tag.ToString
MsgBox(strFileName.ToString)
Process.Start(strFileName)
End Sub

Here's an example using your hard-coded folder:
Dim ImageExtension As String = "*.jpg"
Dim FolderPath As String = "C:\Users\Mohammed Waseem\Pictures\"
For Each FilePath As String In System.IO.Directory.GetFiles(FolderPath, ImageExtension)
Try
Dim NewImage As Image = Image.FromFile(FilePath)
NewImage = NewImage.GetThumbnailImage(NewImage.Width * 0.5, NewImage.Height * 0.5, AddressOf abort, System.IntPtr.Zero)
Dim P As New PictureBox
P.SizeMode = PictureBoxSizeMode.AutoSize
P.Image = NewImage
AddHandler P.Click, AddressOf PictureBox1_Click
FlowLayoutPanel1.Controls.Add(P)
ListBox1.Items.Add(System.IO.Path.GetFileName(FilePath))
Catch ex As Exception
End Try
Next

Related

Add Event to Picture Box dynamically vb.net

I'm trying to add pictureboxes dynamically in vb.net.
If i play with the vars, changing the "i" value i can add the images and the event to the last picturebox created (i can only click the last images).
But when i use the code below, it says the there's something out of boundaries ( Index outside the bounds of the matrix ).
What am i doing wrong? Tks
Imports System.IO
Public Class FormMain
Dim Path1 As String = Path.GetDirectoryName(Application.ExecutablePath) & "\Source\Images\1.png"
Dim Path2 As String = Path.GetDirectoryName(Application.ExecutablePath) & "\Source\Images\2.png"
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CreateImages()
End Sub
Dim i As Integer
Dim Logo(i) As PictureBox
Sub CreateImages()
Dim i As Integer = TextBoxNumberImages.Text
For i = 0 To i - 1
Logo(i) = New PictureBox
Logo(i).Name = "Image" + Str(i)
Panel1.Controls.Add(Logo(i))
Logo(i).Image = Image.FromFile(Path1)
Logo(i).SizeMode = PictureBoxSizeMode.StretchImage
AddHandler Logo(i).Click, AddressOf _Click
Next
End Sub
'------ADD EVENT----
Dim IsImageSelected(i) As Boolean
Private Sub _Click(ByVal sender As Object, ByVal e As EventArgs)
If IsImageSelected(i) = False Then
Logo(i).Image = Image.FromFile(Path2)
IsImageSelected(i) = True
Else
Logo(i).Image = Image.FromFile(Path1)
IsImageSelected(i) = False
End If
End Sub
----EDIT----
I just changed the var declaration to inside of the function:
Sub CreateImages()
Dim i As Integer = TextBoxNumberImages.Text
Dim Logo(i) As PictureBox
For i = 0 To i - 1
Logo(i) = New PictureBox
Logo(i).Name = "Image" + Str(i)
Panel1.Controls.Add(Logo(i))
Logo(i).Image = Image.FromFile(Path1)
Logo(i).SizeMode = PictureBoxSizeMode.StretchImage
AddHandler Logo(i).Click, AddressOf _Click
Next
End Sub
Now it creates the images the way i want, but i can't access the pictureboxes in the event. Help?
Don't use an array, use a List(Of PictureBox) instead. You could also store the selected state in the Tag() of the PictureBox. To get a reference to the PictureBox that was clicked, cast the Sender parameter. All together it would look something like this:
Private Logo As New List(Of PictureBox)
Sub CreateImages()
Dim i As Integer = TextBoxNumberImages.Text
For i = 0 To i - 1
Dim pb As New PictureBox
pb = New PictureBox
pb.Tag = False ' <-- initial not selected state
pb.Name = "Image" + Str(i)
Panel1.Controls.Add(pb)
pb.Image = Image.FromFile(Path1)
pb.SizeMode = PictureBoxSizeMode.StretchImage
AddHandler pb.Click, AddressOf _Click
Logo.Add(pb)
Next
End Sub
Private Sub _Click(ByVal sender As Object, ByVal e As EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
Dim selected As Boolean = DirectCast(pb.Tag, Boolean)
If selected = False Then
pb.Image = Image.FromFile(Path2)
Else
pb.Image = Image.FromFile(Path1)
End If
pb.Tag = Not selected ' toggle selected state
End Sub

How do I get a value from a dynamic control?

I've got a form with a picturecontrol (default to black bg) and I have a flowlayoutpanel underneath. On the form's load it cycles through a folder of images and creates a thumbnail (picturecontrol) inside the flowlayoutpanel. What I want to do is dynamically add a click event to let the user change the main picturecontrol image with one of the thumbnails.
Private Sub TabImageLoad()
Dim apppath As String = Application.StartupPath()
Dim strFileSize As String = ""
Dim di As New IO.DirectoryInfo(apppath + "\images")
Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
Dim fi As IO.FileInfo
For Each fi In aryFi
If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
Dim temp As New PictureBox
temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
temp.Width = 100
temp.Height = 75
temp.Name = fi.ToString
temp.Visible = True
temp.SizeMode = PictureBoxSizeMode.StretchImage
AddHandler temp.Click, AddressOf Me.temp_click
FlowLayoutPanel1.Controls.Add(temp)
End If
Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
PictureBox1.Image = temp.Image
End Sub
This is my code for the sub that gets the images (note the addhandler attempt) and the sub that links to the addhandler. As you've probably guessed the addhandler doesn't work because "temp" is not declared in the temp_click sub.
Any suggestions?
The sender argument is always the control that triggered the event, in this case a PictureBox:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
PictureBox1.Image = pb.Image
End Sub
I suggest you to use:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)
Then validate with
if pbDynamic IsNot Nothing Then
PictureBox1.Image = pbDynamic.image
end if
This way you avoid runtime errors and null pointer exceptions

For Next or a different loop for URL Icon Load

I have an app that basically is a launcher for various web pages. I am trying to, OnLoad, to populate all the pictureBoxes in my form with the FavICON for each URL. 25 to be exact. Should I use a For and Next or some other kind of looping method? New to the looping part so all and any help is appreciated.
My code to load just one single PictureBox is the following:
Private Sub MainFormWPL_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Dim WebICON As New WebBrowser
MainURLLoader.Navigate(Label1.Text)
'URLText.Text = WebBrowser1.Url.ToString
Try
Dim url As Uri = New Uri(Label1.Text)
If url.HostNameType = UriHostNameType.Dns Then
Dim icon = "http://" & url.Host & "/favicon.ico"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(icon)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream
Dim favicon = Image.FromStream(stream)
PictureBox1.Image = favicon
Else
End If
Catch ex As Exception
End Try
End Sub
Assuming you have Label1 --> PictureBox1, all the way to Label25 --> PictureBox25:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches() As Control
For i As Integer = 1 To 25
matches = Me.Controls.Find("Label" & i, True)
If matches.Length > 0 Then
Dim website As String = matches(0).Text
matches = Me.Controls.Find("PictureBox" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is PictureBox Then
Dim PB As PictureBox = DirectCast(matches(0), PictureBox)
Task.Run(New Action(Sub() GetFavIcon(website, PB)))
End If
End If
Next
End Sub
Private Sub GetFavIcon(ByVal website As String, ByVal PB As PictureBox)
Dim url As Uri = New Uri(website)
If url.HostNameType = UriHostNameType.Dns Then
Dim icon = "http://" & url.Host & "/favicon.ico"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(icon)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream
Dim favicon = Image.FromStream(stream)
PB.Invoke(New MethodInvoker(Sub() PB.Image = favicon))
response.Close()
End If
End Sub
End Class

Dynamic button click event not able to call a function vb.net

The TabLoad() function doesn't seem to be working on clicking of this dynamic button. The aim of this button click event is that it deletes text from a text file and loads the form again.
Below is the complete code. The TabLoad() function is in the NextDelbtn_Click sub at the end.
Also any suggestion regarding change of code is appreciated.
Imports System.IO
Public Class Form1
Dim str As String
Dim FILE_NAME As String = "D:\1.txt"
Dim file_exists As Boolean = File.Exists(FILE_NAME)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please enter text that you want to save", MsgBoxStyle.Information, "TOCC Error")
Else
str = TextBox1.Text
Dim fs As FileStream = Nothing
If (Not File.Exists(FILE_NAME)) Then
fs = File.Create(FILE_NAME)
Using fs
End Using
End If
If File.Exists(FILE_NAME) Then
Dim sw As StreamWriter
sw = File.AppendText(FILE_NAME)
sw.WriteLine(str)
sw.Flush()
sw.Close()
TabLoad()
TextBox1.Text = ""
End If
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TabControl1.SelectedIndex = TabControl1.TabIndex + 1
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TabLoad()
End Sub
Private Sub Nextbtn_Click(sender As Object, e As EventArgs)
Dim s As String = DirectCast(DirectCast(sender, Button).Tag, Label).Text
Clipboard.SetText(s)
End Sub
Private Sub TabLoad()
Dim i As Integer = 1
For Each line As String In System.IO.File.ReadAllLines(FILE_NAME)
Dim NextLabel As New Label
Dim Nextbtn As New Button
Dim NextDelbtn As New Button
NextLabel.Text = line
Nextbtn.Text = "Copy"
NextDelbtn.Text = "Delete"
NextLabel.Height = 22
Nextbtn.Width = 55
Nextbtn.Height = 22
NextDelbtn.Width = 55
NextDelbtn.Height = 22
Nextbtn.BackColor = Color.WhiteSmoke
NextLabel.Tag = Nextbtn
Nextbtn.Tag = NextLabel
NextDelbtn.Tag = NextLabel
NextDelbtn.BackColor = Color.WhiteSmoke
NextLabel.BackColor = Color.Yellow
TabPage2.Controls.Add(NextLabel)
TabPage2.Controls.Add(Nextbtn)
TabPage2.Controls.Add(NextDelbtn)
NextLabel.Location = New Point(10, 10 * i + ((i - 1) * NextLabel.Height))
Nextbtn.Location = New Point(120, 10 * i + ((i - 1) * Nextbtn.Height))
NextDelbtn.Location = New Point(180, 10 * i + ((i - 1) * NextDelbtn.Height))
AddHandler Nextbtn.Click, AddressOf Me.Nextbtn_Click
AddHandler NextDelbtn.Click, AddressOf Me.NextDelbtn_Click
i += 1
Next
File.WriteAllLines(FILE_NAME,
File.ReadAllLines(FILE_NAME).Where(Function(y) y <> String.Empty))
End Sub
Private Sub NextDelbtn_Click(sender As Object, e As EventArgs)
Dim btn As Button = CType(sender, Button)
Dim s As String = (btn.Tag).Text
Dim lines() As String = IO.File.ReadAllLines(FILE_NAME)
Using sw As New IO.StreamWriter(FILE_NAME)
For Each line As String In lines
If line = s Then
line = ""
End If
sw.WriteLine(line)
Next
sw.Flush()
sw.Close()
TabLoad()
End Using
End Sub
End Class
Your problem appears to be that you're initializing new controls but you're not changing the controls on the form or even creating a new form.

pics being removed from the flowlayoutpanel

hello guys im making this application in VB that loads picture boxes from a file into a flowlayoutpanel and adds a click handler to each pic in order to display them in a bigger size. however when they are clicked are removed from the layoutpanel and i dont want that and dont understand why is happening. this is my code:
Imports System.IO
Public Class Form1
Private folderPath As String
Private pics() As PictureBox
Private Sub OpenToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles OpenToolStripMenuItem.Click
FolderBrowser.SelectedPath = Directory.GetCurrentDirectory
If FolderBrowser.ShowDialog() = DialogResult.Cancel Then
Return
End If
folderPath = FolderBrowser.SelectedPath()
Dim fileNames As String() = Directory.GetFiles(folderPath)
If fileNames.Length = 0 Then
MessageBox.Show("Unable to find any image files")
Return
End If
Me.Text = folderPath
ReDim pics(fileNames.Length - 1)
For i As Integer = 0 To fileNames.Length - 1
pics(i) = New PictureBox()
With pics(i)
.Size = New System.Drawing.Size(300, 200)
.SizeMode = PictureBoxSizeMode.Zoom
.Image = New Bitmap(fileNames(i))
FlowPanel.Controls.Add(pics(i))
AddHandler pics(i).Click, AddressOf pics_Click
End With
Next
End Sub
Private Sub pics_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pic As PictureBox = DirectCast(sender, PictureBox)
With pic
.Size = New System.Drawing.Size(500, 500)
.SizeMode = PictureBoxSizeMode.Zoom
RemoveHandler pic.Click, AddressOf pics_Click
End With
Dim frm As New Form2
FlowPanel.Controls.Add(pic)
frm.FlowLayoutPanel1.Controls.Add(pic)
frm.ShowDialog()
End Sub
End Class
frm.FlowLayoutPanel1.Controls.Add(pic)
A control can have only one parent. So moving it to the new form will remove it from FlowPanel. If you want a copy then you'll have to create a new PictureBox:
Dim pic As PictureBox = DirectCast(sender, PictureBox)
Dim newpic As PictureBox = new PictureBox()
With newpic
.Size = New System.Drawing.Size(500, 500)
.SizeMode = PictureBoxSizeMode.Zoom
.Image = pic.Image
End With
Dim frm As New Form2
frm.FlowLayoutPanel1.Controls.Add(newpic)
frm.ShowDialog()