Hello,
I would use a custom PictureBox so there is no need to cast.
Public Class MyPictureBox
Inherits PictureBox
''' <summary>
''' Primary key from database or DataTable
''' </summary>
''' <returns></returns>
Public Property PrimaryKey() As Integer
End Class
Simple demo to create one (and you can get it from the toolbox rather than hand code it)
Dim myBox = New MyPictureBox
myBox.PrimaryKey = 3
Find by primary key which is hard code here but the 3
can come from where ever. I check to see if it's found then for this simple example remove the background image.
Dim pb = FlowLayoutPanel1.Controls.OfType(Of MyPictureBox).FirstOrDefault(Function(pbox) pbox.PrimaryKey = 3)
If pb IsNot Nothing Then
pb.BackgroundImage = Nothing
End If
Second code sample
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pb = FlowLayoutPanel1.Controls.OfType(Of MyPictureBox).FirstOrDefault(Function(pbox) pbox.PrimaryKey = 3)
If pb IsNot Nothing Then
Text = $"From button click event: {pb.PrimaryKey}"
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
FlowLayoutPanel1.Controls.OfType(Of MyPictureBox).ToList().ForEach(
Sub(pb)
AddHandler pb.Click, AddressOf MyPictureBox_Click
End Sub)
End Sub
Private Sub MyPictureBox_Click(sender As Object, e As EventArgs)
Dim pb As MyPictureBox = CType(sender, MyPictureBox)
Text = $"From Picture click event: {pb.PrimaryKey}"
If pb.BorderStyle = BorderStyle.None Then
pb.BorderStyle = BorderStyle.Fixed3D
Else
pb.BorderStyle = BorderStyle.None
End If
End Sub
End Class