none
Problem using AddHandler and AddressOF in vb.net RRS feed

  • Question

  • I am using this code :

        Dim img As Image
        Private Sub SendMail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            For Each fi As FileInfo In New DirectoryInfo("D:\emojis\1").GetFiles()
                Dim pbx As New PictureBox
                pbx.Width = 32
                pbx.Height = 32
                pbx.Image = Image.FromFile(fi.FullName)
                AddHandler pbx.Click, AddressOf pbx_click
                FlowLayoutPanel1.Controls.Add(pbx)
    
            Next
        End Sub
        Friend Sub pbx_click(sender As Object, e As EventArgs)
            img = pbx.Image
            Clipboard.SetImage(img)
            bodytxt.Paste()
        End Sub

    Basically my motive is i want add image to a richtextbox(bodytxt) by clicking on pictureboxes(pbx)that are generated on form's load event.But in the pbx_click event i can't use : image=pbx.image : It says PBX NOT DECLARED.So how do i fix it?

    Wednesday, November 8, 2017 7:34 AM

All replies

  • But in the pbx_click event i can't use : image=pbx.image : It says PBX NOT DECLARED.So how do i fix it?

    You have declared the variable PBX within the function SendMail_Load(), so its usage is restricted to that function. If you want to refer to it from code in other places, then it should be declared at a level (eg, form level) where it is accessible to all functions.
    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/scope
    Wednesday, November 8, 2017 8:03 AM
  •  In your pbx_click sub,  you need to cast the sender object to a PicturBox and then get the Image from it.  The sender will be the PictureBox that raised the event,  the one you clicked.  For example...

        Friend Sub pbx_click(sender As Object, e As EventArgs)
            img = CType(sender, PictureBox).Image 'cast the sender object to a PictureBox to get the image from it
            Clipboard.SetImage(img)
            bodytxt.Paste()
        End Sub
    


    If you say it can`t be done then i`ll try it

    • Proposed as answer by Cor Ligthert Wednesday, November 8, 2017 12:04 PM
    Wednesday, November 8, 2017 10:34 AM
  • I prefer the one from Ray but the solution from Acamar goes as well. Be aware using the "Friend" accessor is senseless. It is simply private to the class, in this context it is only confusing.


    Success
    Cor


    • Edited by Cor Ligthert Wednesday, November 8, 2017 12:06 PM
    Wednesday, November 8, 2017 12:05 PM