eMbs
eMbs

Reputation: 79

vb.net assign image to picturebox through panel controls

I'm writing a program of a card game in VB.NET. I have encountered a problem. Computer_Flow is declared like System.Windows.Forms.Panel manualy on design window. I have created a picture box like this programmaticly:

Dim P As PictureBox = New PictureBox  
P.Size = New Point(Cards_Width, Cards_Height)  
P.SizeMode = PictureBoxSizeMode.StretchImage  
P.Image = Image.FromFile(Images_Folder_Path & "Back.png")   
P.Tag = Deck(DI)    
P.Margin = New Padding(1)  
Computers_Hand(DI) = Deck(DI)  
Computer_Flow.Controls.Add(P)

Later on I want to change that PictureBox image. I'm trying to change it like that:

Computer_Flow.Controls(i).image = Image.FromFile(Images_Folder_Path & "Back.png")  

But I get an error which says: 'image' is not a member of System.Windows.Forms.Control'.

Who can help me to solve this problem?

Thanks!

Upvotes: 2

Views: 3984

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to cast that control to picture box in order to get your result. Try this out,

CType(Computer_Flow.Controls(i),PictureBox).image=Image.FromFile(Images_Folder_Path & "Back.png")

CType

EDIT:

you can easily avoid that invalidCastException in an effective manner like this,

If TypeOf Computer_Flow.Controls(i) Is PictureBox then

CType(Computer_Flow.Controls(i),PictureBox).image=Image.FromFile(Images_Folder_Path & "Back.png")

End If

TypeOf

Upvotes: 1

SolarBear
SolarBear

Reputation: 4619

You're accessing a list of Control, a base class which does not contain an Image member.

You'll need to typecast it as a PictureBox:

Dim pb As PictureBox = TryCast(Computer_Flow.Controls(i), PictureBox)

If Not pb Is Nothing Then
     pb.image = Image.FromFile(Images_Folder_Path & "Back.png")
End If

That way VB will know it really isn't just a Control but a PictureBox, with an Image member. I suggest adding the TryCast, just in case.

Upvotes: 1

Related Questions