Procedure is checks if picturebox is empty and if it has tag. Not working properly - vb.net

I have 4 picture boxes on my form. I want my procedure to check if the picture does not contain a string tag, if it does not contain a string Tag, then place the picture on that box. I run the procedure but nothing happens no error. It simply does not load my picture. My best guess is that I have my IF condition wrong. Here is my procedure:
Private Sub btnAddImage_Click(sender As Object, e As EventArgs) Handles btnAddImage.Click
ofdBrowsePictures.Multiselect = False
ofdBrowsePictures.Title = "Select Image to Upload"
ofdBrowsePictures.Filter = "Image Files |*.jpg*"
If ofdBrowsePictures.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim PBs() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
Dim nextPB = PBs.Where(Function(x) IsNothing(x.Image)).FirstOrDefault
Dim nextTag = PBs.Where(Function(x) IsNothing(x.Tag)).FirstOrDefault
If Not IsNothing(nextTag) Then
nextPB.ImageLocation = ofdBrowsePictures.FileName
End If
End If
End Sub

You're using "nextPB" which is checking for no image. Your "nextTag" variable, however, is checking for no Tag. Change it to:
Private Sub btnAddImage_Click(sender As Object, e As EventArgs) Handles btnAddImage.Click
ofdBrowsePictures.Multiselect = False
ofdBrowsePictures.Title = "Select Image to Upload"
ofdBrowsePictures.Filter = "Image Files |*.jpg*"
If ofdBrowsePictures.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim PBs() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
Dim nextTag = PBs.Where(Function(x) IsNothing(x.Tag)).FirstOrDefault
If Not IsNothing(nextTag) Then
nextTag.ImageLocation = ofdBrowsePictures.FileName
End If
End If
End Sub

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 Loop works not working, or giving error. Works when conditions are reversed

I don't know if its the late hour, but I am working on the following array For Loop:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pboxes() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
For i As Integer = 0 To pboxes.Count - 1
If pboxes(i).Image Is My.Resources.list Then
pboxes(i).Image = Nothing
End If
Next
End Sub
The loop is supposed to check if any of the picture boxes in the array have an Image called List stored on the Resources folder in them. If it does, set the image to Nothing. However, I run it and nothing happens., no errors, nothing.
So I reversed my For Loop as follows to see what happens:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pboxes() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
For i As Integer = 0 To pboxes.Count - 1
If pboxes(i).Image Is Nothing Then
pboxes(i).Image = My.Resources.list
End If
Next
End Sub
This works but is not what I want, I want the opposite.
What am I doing wrong here?
One option is if you set the pictures in the box programatically, set My.Resources.list to be referenced by a global variable, ie Public pbList = My.Resources.list
Then, when you set the picture initially, use that variable, so: picMainImage.Image = pbList
Finally, in your If statement, you should then be able to check If pboxes(i) is pbList Then...
Once it becomes a variable, it seems to become static and therefore wherever you use it, it will always be the same.
EDIT: some actual code that I used a few months back:
In the module (outside sub)
Public pbimage As System.Drawing.Image = My.Resources.placeholder
Then in the Sub
If imgpath <> "" Then
Me.lblImg.ImageLocation = imgpath
Else
Me.lblImg.ImageLocation = Nothing
Me.lblImg.Image = pbimage
End If
and then this is what I use for all pictures without issues (its a function that I have run when you click on an image - if its the placeholder then you can browse for an image and save it to a data folder, otherwise it does nothing)
Private Sub changeImg(sender As Object, e As MouseEventArgs) Handles {ALL YOUR IMAGES}.Click
If TypeOf sender Is PictureBox Then
If DirectCast(sender, PictureBox).Image Is pbimage Then
Dim ofd As New OpenFileDialog
ofd.Title = "Please select image"
ofd.Filter = "Image Files|*.jpg"
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim rn As New Random
Dim r As Long = rn.Next(111111, 999999)
Dim newfilename As String = My.Settings.dataPath & r.ToString & Format(Now, "ddmmyy") & ".jpg"
Try
FileCopy(ofd.FileName, newfilename)
DirectCast(sender, PictureBox).ImageLocation = newfilename
Catch ex As Exception
MessageBox.Show("Check permissions to the Data folder", "Permissions error")
End Try
End If
End If
End If
End Sub
Images cannot be compared that way because the image is copied into memory and will always be different even if the pixels match. Compare the pixels directly to find out if the image is the same.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pboxes() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
For i As Integer = 0 To pboxes.Count - 1
If IsSameImage(pboxes(i).Image, My.Resources.list) = True Then
pboxes(i).Image = Nothing
End If
Next
End Sub
Public Function IsSameImage(ByVal oBitmap1 As Bitmap, ByVal oBitmap2 As Bitmap) As Boolean
For x = 0 To oBitmap1.Width - 1
For y = 0 To oBitmap2.Height - 1
If Not oBitmap1.GetPixel(x, y) = oBitmap2.GetPixel(x, y) Then
Return False
End If
Next
Next
Return True
End Function

Add a Link Button on Each Click Event in VB

I have a drop down list with a bunch of product names in it with an add button on the side. Everytime I press the add button, I want a Linkbutton to appear with the name of the product. I did the pnl.Controls.Add(New LinkButton), but it only adds one and then goes away next time I go to click. Here is the code I have right now that is making a LinkButton appear at click, just can't figure out how to alter the logic to add a new one each time.
Private Sub btnAddLinkedProjects_Click(sender As Object, e As EventArgs) Handles btnAddLinkedProjects.Click
lbLinkedProject.Visible = True
lbLinkedProject.Text = ddlParentProject.SelectedItem.Text
End Sub
I have a linkbutton in my designer that is set to invisible until it's clicked. Ultimately, when the link button of the project is clicked on, it fills in all of the fields like this
Private Sub lbLinkedProject_Click(sender As Object, e As EventArgs) Handles lbLinkedProject.Click
Dim intParentRecID As Integer
Dim pid As Project = Nothing
Dim intCityState As Integer = 0
Dim strState As String = ""
Dim cs As nsCityState = Nothing
intParentRecID = Integer.Parse(ddlParentProject.SelectedValue)
pid = oDesignCon.getProjectByRecID(intParentRecID)
If pid Is Nothing Then
Else
intCityState = pid.CityState
cs = New nsCityState(intCityState)
If cs Is Nothing Then
Else
strState = cs.StateShort
Me.ddlAddState.SelectedValue = strState
Call HandleAddStateChanged()
End If
Call nsLinqFormBinder.LoadContainer(Me.pnlCreateNewPID, pid)
Me.ddlAddAssignTo.SelectedIndex = 0
End If
End Sub
What's wrong if you just create new LinkButton as usual :
Private Sub btnAddLinkedProjects_Click(sender As Object, e As EventArgs) Handles btnAddLinkedProjects.Click
'create & prepare new LinkButton'
Dim newLinkedProject As New LinkButton
newLinkedProject.Visible = True
newLinkedProject.Text = ddlParentProject.SelectedItem.Text
'register event handler'
AddHandler newLinkedProject.Click, AddressOf Me.lbLinkedProject_Click
'add the LinkButton to panel'
pnl.Controls.Add(newLinkedProject)
End Sub

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

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