find control in FlowLayoutPanel

AMER SAID 396 Reputation points
2021-04-08T04:12:32.793+00:00

hi

I added PictureBox to the FlowLayoutPanel Each image takes a value from the datatable by tag = id column. What I want is to choose the image that has the number that I specify

my code Does not select any image

For Each item As Control In FlowLayoutPanel.Controls

        If TypeOf item Is PictureBox Then
            If item.Tag = "3" Then
                item.BackgroundImage = Nothing
                item.Select()
            End If
        End If
    Next
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,579 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,191 Reputation points
    2021-04-08T18:00:20.99+00:00

    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
    
    1 person found this answer helpful.
    0 comments No comments