OtherBarry OtherBarry - 6 months ago 9
Vb.net Question

Using Events and Properties of code created objects

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

Answer

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.

Comments