JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Adding Buttons at Run Time

Your new program lets the user add options to customize things, and you want to display a new button for each option. Is there a way to add buttons to a Visual Basic program at run time?

Yes, there is. In fact, we've already seen how to do that earlier in this chapter, in the topic "Imitating Control Arrays." We declared new buttons there and added them to an imitation control array. There, all the buttons used the same event handler, but we can modify that code so each new button has its own event handler, like this:

Public Class Form1
    Inherits System.Windows.Forms.Form
    Dim WithEvents Button1 As Button
    Dim WithEvents Button2 As Button
    Dim WithEvents Button3 As Button
    Friend WithEvents Button4 As Button
    Friend WithEvents TextBox1 As TextBox

    'Windows Form Designer generated code

    Private Sub Button4_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button4.Click
        Button1 = New Button()
        Button2 = New Button()
        Button3 = New Button()

        Button1.Size = New Size(80, 30)
        Button1.Location = New Point(115, 20)
        Button1.Text = "Button 1"

        Button2.Size = New Size(80, 30)
        Button2.Location = New Point(115, 60)
        Button2.Text = "Button 2"

        Button3.Size = New Size(80, 30)
        Button3.Location = New Point(115, 100)
        Button3.Text = "Button 3"

        Controls.Add(Button1)
        Controls.Add(Button2)
        Controls.Add(Button3)

        AddHandler Button1.Click, AddressOf Button1_Click
        AddHandler Button2.Click, AddressOf Button2_Click
        AddHandler Button3.Click, AddressOf Button3_Click
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs)
        TextBox1.Text = "You clicked button 1"
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs)
        TextBox1.Text = "You clicked button 2"
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs)
        TextBox1.Text = "You clicked button 3"
    End Sub

End Class

That's all it takes.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor