WHAT'S NEW?
Loading...

Make a button and label at runtime in VB.NET


To create a control at design time is simply easy because you are free to decide which controls you want to add and no more codes needed to create controls. However, it’s more convenient to create controls at runtime specifically if you don’t know how many pieces of data you will need to display until runtime. In addition, displays unknown amounts of data in various controls is more flexible than creating at design time. For instance, you may want to output your result in label or to trigger a button to add controls to display a message, at runtime you’re free where to set its position of every control to display on your forms by setting SetBounds method.

To create a label at runtime, simply add this piece of code in you button.

 Dim lblNewLabel As New Label
        lblNewLabel.SetBounds(10, 10, 100, 25)
        lblNewLabel.Text = "Hello"
        Me.Controls.Add(lblNewLabel)

First declare a variable of type Label and initializes it with the New keyword. SetBounds methods set the position x, y, w, and h SetBounds(x,y,w,h) where the label shows in the forms.

If you are going to display the control in a container, you might use the statement grpLabels.Controls.Add(lblNewLabel)

Create a button at runtime using WithEvents keywords.

Sample Code #1.
Public Class FrmCreateButton
    Private WithEvents btnNewButton As Button

    Private Sub btnCreateButton_Click(sender As System.Object, e As System.EventArgs) Handles btnCreateButton.Click
        btnNewButton = New Button
        btnNewButton.SetBounds(16, 16, 80, 23)
        btnNewButton.Text = "Say Hi"
        Me.Controls.Add(btnNewButton)
    End Sub

    Private Sub btnNewButton_Click() Handles btnNewButton.Click
        MessageBox.Show("Now, I'm created")
    End Sub

End Class

This approach, when the user click btnCreateButton, Say Hi button created. When the users click btnNewButton_Click, event handler executes and displays a message.

Sample Code #2
Private Sub btnCreateHelloButton_Click(sender As System.Object, e As System.EventArgs) Handles btnCreateHelloButton.Click
        Dim CreateHelloButton As New Button
        CreateHelloButton.SetBounds(250, 65, 80, 23)
        CreateHelloButton.Text = "Hello"
        Me.Controls.Add(CreateHelloButton)

        AddHandler CreateHelloButton.Click, AddressOf Hello
    End Sub
    Private Sub Hello()
        MessageBox.Show("Hello Visual Basic.Net")
    End Sub

One solution to this dilemma is to use the AddHandler statement to add event handlers to the new controls. When you click the btnCreateHelloButton, its click event handler creates a new button object, storing it in a locally declared variable.

When you compare sample #1 and sample #2 is quite different.

1 comment: Leave Your Comments