By Abir Atarthy
Last week one of you asked me how to add new controls dynamically in VB.Net.
So i am explaining it here.
In many cases you may want
· To have a single method handle the events of multiple controls
· To dynamically add new controls to your form at runtime
In VB6.0 we had control array for this. But Dotnet do not have control arrays. But the same can be done in different ways here.
Consider the following example:
Create a new form and add two buttons. Change the name of one button to bt1. Open the code window of bt1.click event. To make this method respond to the Button2.Click event as well, simply add the Button2.Click event handler to the end of the Handles list and then add some simple code to display a message box indicating what button triggered the event. Here is the code:
Private Sub bt1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt1.Click, Button2.Click
Dim buttonClicked As Button
buttonClicked = CType(sender, Button)
' Display which button was clicked
MessageBox.Show("You clicked " & buttonClicked.Text)
End Sub
Run the program and click the two buttons. Each one will trigger the event and display a message box with the appropriate text from the button that was clicked.
The above code uses a strongly typed variable buttonClicked. The CType function converts the generic type to a specific type so that it can be assigned to the strongly typed variable. If the object passed as a parameter is not of type Button, you get a trappable error.
Now enhance the program to add a third button dynamically at runtime. Add another button to your form and name it as addnewbutton. It will trigger the addition of button3. Add the following code to click event of addnewbutton.
Private Sub addnewbutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addnewbutton.Click
Dim newButton As Button
' Create the new control
newButton = New Button()
' Set it up on the form
newButton.Location = New System.Drawing.Point(184, 12)
newButton.Size = New System.Drawing.Size(75, 23)
newButton.Text = "Button3"
' Add it to the form's controls collection
Me.Controls.Add(newButton)
' Hook up the event handler.
AddHandler newButton.Click, AddressOf Me.bt1_Click
End Sub
When the addnewbutton button is clicked, the code creates a new button, sets its size and position, and then does two essential things. First, it adds the button to the form’s controls collection, and second, it connects the Click event of the button to the method that handles it.
I am adding a sample run of the program for your better understanding.
No comments:
Post a Comment