Nick LaMarca
Nick LaMarca

Reputation: 8198

Adding events dynamically

Here's a scernerio that will get what I am trying to accomplish....

Say I have a form with a textbox to enter a number and a button called "Create" When a user enters a number and clicks create the form gets populated with the number of buttons entered in the textbox and the title of the buttons are labeled by consecutive numbers.

For example if you enter 5 the form will populate with 5 buttons labeled button1, button2, ...button5

When you click on these newly created buttons a messagebox will popup stating the buttons name.

Basically I need to know how to create events and populate them with code I guess

dynamically.

Please respond in a solution for a windows app not web. No JavaScript.

Please can someone respond with a code example this idea is a little foggy to me

Upvotes: 0

Views: 65

Answers (1)

NoAlias
NoAlias

Reputation: 9193

        'Make sure that the textbox contains a number.
    If IsNumeric(TextBox1.Text) Then

        'Make sure that it's a positive number.
        If CInt(TextBox1.Text) > 0 Then

            For i = 1 To CInt(TextBox1.Text)

                Dim x As New Button
                x.Name = "Button" & i.ToString
                x.Top = 100 + (i * 30) 'To avoid stacking.
                AddHandler x.Click, AddressOf y 'Add the event here.

                'Add it to the form.
                Controls.Add(x)

            Next

        End If

    End If

    Private Sub y(ByVal sender As System.Object, ByVal e As System.EventArgs)

    MsgBox(CType(sender, Button).Name)

End Sub

Upvotes: 2

Related Questions