简体   繁体   中英

Which auto generated picturebox was clicked? VB.net

I have the following code. Im trying to find out which of the 64 pictureboxes was clicked:

        For i As Integer = 1 To 8
        For j As Integer = 1 To 8
            SpilleBræt(i, j) = New PictureBox 'Opretter picturebox
            If (i + j) Mod 2 = 1 Then
                Me.SpilleBræt(i, j).BackgroundImage = Skak.My.Resources.DarkTile
            Else
                Me.SpilleBræt(i, j).BackgroundImage = Skak.My.Resources.LightTile
            End If

            'Placering, størrelse, m.v.
            Me.SpilleBræt(i, j).Location = New System.Drawing.Point((i - 1) * 103, (j - 1) * 103)
            Me.SpilleBræt(i, j).Size = New System.Drawing.Size(100, 100)
            Me.SpilleBræt(i, j).Name = "SpilleBrik" & i & j
            Me.PanelSpilleBræt.Controls.Add(Me.SpilleBræt(i, j))
        Next j
    Next i

Thanks.

In order to handle a click event, the first thing you'll need is a click handler. Could be something as simple as this:

Private Sub PictureBox_Click(ByVal sender As Object, ByVal e As EventArgs)  
    ' Do something in here
End Sub

When you create your PictureBox controls, bind the handler to their click event:

AddHandler Me.SpilleBræt(i, j).Click, AddressOf PictureBox_Click
Me.PanelSpilleBræt.Controls.Add(Me.SpilleBræt(i, j))

What this should do is invoke the PictureBox_Click method any time the user clicks on the PictureBox . Within that method, sender is the element which was clicked:

Private Sub PictureBox_Click(ByVal sender As Object, ByVal e As EventArgs)  
    Dim clickedBox As PictureBox
    clickedBox = CType(sender, PictureBox)
    ' clickedBox is the element which was clicked
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM