change picturebox's image at runtime

ramone

Freshman
Joined
Sep 29, 2005
Messages
26
how can i change the image of a picturebox control at runtime when mouse hovers it??
heres my code

Visual Basic:
Private Sub hoverDiente(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles d1.MouseHover, d2.MouseHover
        sender = CType(sender, PictureBox)
        Dim tempStr As String = sender.name
        tempStr.Replace("d", "")
        MsgBox(Me.path)
        sender.Image = New Bitmap(Me.path + "\\path\\" + tempStr + ".jpg")

    End Sub

so far i have an 'invalid argument' error when calling sender.image=new bitmap()

thanks for your help
 
I know that this is not what you were asking and I'm not trying to rag on your coding, but I just want to point this out, in case you aren't aware. Note the underlined code

Visual Basic:
Private Sub hoverDiente(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles d1.MouseHover, d2.MouseHover
        [U][B]sender = CType(sender, PictureBox)[/B][/U]
        Dim tempStr As String = sender.name
        tempStr.Replace("d", "")
        MsgBox(Me.path)
        sender.Image = New Bitmap(Me.path + "\\path\\" + tempStr + ".jpg")

    End Sub
This line casts "sender" to type PictureBox, and stores the reference back into the "sender" variable, whose type is Object, essentially uncasting to object and forcing you to use late binding when you access sender.Image. This would be a better approach.
Visual Basic:
'At the top of the file
Option Strict On

'Hover image code
Private Sub hoverDiente(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles d1.MouseHover, d2.MouseHover
        [U][B]Dim picSender As PictureBox = CType(sender, PictureBox)[/B][/U]
        Dim tempStr As String = picSender.name
        tempStr.Replace("d", "")
        MsgBox(Me.path)
        picSender.Image = New Bitmap(Me.path + "\\path\\" + tempStr + ".jpg")

    End Sub

Another note, this one related to the issue at hand: when constructing file names, I recommend using the IO.Path class to avoid issues with missing/doubled backslashes.

Visual Basic:
'At the top of the file
Option Strict On

'Hover image code
Private Sub hoverDiente(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles d1.MouseHover, d2.MouseHover
        Dim picSender As PictureBox = CType(sender, PictureBox)
        Dim tempStr As String = picSender.name
        tempStr.Replace("d", "")
        MsgBox(Me.path)
        [B][U]picSender.Image = New Bitmap(IO.Path.Combine(_ 
            Me.path & "\\path\\" & tempStr & ".jpg")[/U][/B]

    End Sub
 
Back
Top