0

I am adding many panels to a FlowLayoutPanel, by going through a database and adding a panel with relevant labels for each entry in the database. I need to be able to then be able to code what happens when any of the panels are clicked on, but am unable to work out how.

This is the code I use to generate the panels

For i As Integer = 0 To IDs.Count - 1
    Dim testPanel As New Panel With
        {
            .Height = 50,
            .Width = 140,
            .BackColor = Blue,
            .Name = "rPanel" + i.ToString
        }
    FlowLayoutPanel.Controls.Add(testPanel)
 Next

2 Answers 2

1

Add an event handler to the MouseClick event, like this.

For i As Integer = 0 To IDs.Count - 1
    Dim testPanel As New Panel With
        {
            .Height = 50,
            .Width = 140,
            .BackColor = Blue,
            .Name = "rPanel" + i.ToString
        }
    AddHandler testPanel.MouseClick, AddressOf PanelMouseClick
    FlowLayoutPanel.Controls.Add(testPanel)
 Next

Then create a handler sub for the event. Like..

Private Sub PanelMouseClick(sender As Object, e As MouseEventArgs)
    MessageBox.Show("Mouse Clicked")
End Sub

AddHandler allows you to set the event you want to handle. AddressOf lets you set which sub you want the call to handle said event. If you're unsure of the sub signature, you can use Visual Studio to generate none created sub's with the correct signatures.

Sign up to request clarification or add additional context in comments.

2 Comments

That worked wonderfully. Thanks. As a follow up, If I add a label as a control to that panel, is there a way I can make it run the same sub when the label is clicked, only with the panel as the sender instead of the label?
If the event you are addressing has the same signature you can apply multiple events to one handler yes. So yes, you can just add the same click event handler to the label. If you're using an event which signature is different extract your code logic to a separate method and call that from the specific event handlers.
0

Add a handler to the panel, before adding it to the other panel.

AddHandler testPanel.Click, AddressOf Method
FlowLayoutPanel.Controls.Add(testPanel)

Add a new method with sender and eventargs as values:

Private Sub Method(sender As Object, e As EventArgs)
    'Your Code
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.