2


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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

+1 because this is a perfectly reasonable way of doing this. However, it makes more sense to me to add the button corresponding to the item that has just been added to the ComboBox, rather than looping through all of the existing items and adding a button. All you need to do is create the button and add it to your form's Controls collection in the same place where you add an item to your ComboBox.
Good point Cody. In my head I had it that the user was selecting some integer value in the combo box and we were creating the buttons based on that number.
1

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

2 Comments

Also see the question: "Dynamic button click event handler" ... since you probably want to handle the event generated by a click on one of the new buttons.
Can I just point out, you'd be better off using with...so Dim b As Button With {.Name = "Button1", .Size = New Size(30,30), .Location = New Point(12,100)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.