Furqan Sehgal
Furqan Sehgal

Reputation: 4997

Adding buttons at runtime


I want to place a few buttons on my form. The number is unknown at design time. Actually each button will represent an item entered in combo box. So if user adds an item, a button on the form should be added by the code. Please advise how to do it?

Thanks
Furqan

Upvotes: 2

Views: 16013

Answers (2)

Jamie Dixon
Jamie Dixon

Reputation: 54001

You can do this by simply looping over any number (in this case from a combo box) and creating the required number of buttons before adding them to the form.

For i As Integer = 0 To myComboBox.Items.Count - 1
   Dim newButton = new Button()

   // Add some properties, etc. to the button
   newButton.Text = myComboBox.Items(i).ToString()

   MyForm.Controls.Add(newButton)
Next

Upvotes: 2

xpda
xpda

Reputation: 15813

You can use a function like this:

Sub AddButton(ByVal label As String, ByVal location As Point)

Dim b As Button

b = New Button
b.Location = location
b.Text = label
Me.Controls.Add(b)

End Sub

Upvotes: 1

Related Questions