0

I am trying to create an app that will allow a user to add buttons with a provided name to a form. However, I am unsure how to create the button using the user-provided value.

I have tried this

Dim Button_ & ButtonName As New Button

This obviously does not work, does anyone know if this is possible and if so, how I would go about doing it.

I would also need to generate a handler for the button so that I can make it function. For example,

Private Sub button_ & ButtonName & _Click(sender As Object, e As EventArgs) Handles Button_ & ButtonName & .Click
3
  • Why would the user care what the name of a control is? The name of a control is only used in code. Commented Oct 2, 2020 at 21:22
  • stackoverflow.com/questions/11312239/… Just Google "add a control to a form in vb.net" Commented Oct 2, 2020 at 21:24
  • dim btn as new Button() with { .Name = ButtonName, .Text = ButtonName } AddHandler btn.Click, AddressOf SomePredefinedHandler. Or use a Lambda: AddHandler btn.Click, Sub(obj, args) End Sub (End Sub goes on a new line). Better use the first AddHandler syntax. You probably want to add these controls to a collection (e.g., List(Of Button)). Commented Oct 3, 2020 at 1:41

1 Answer 1

0

You can do it simply with:

Dim btn1 As New Button With {
    'Write properties here.
    .Size = New Drawing.Size(10, 10),
    .Visible = True
}

AddHandler btn1.Click, New EventHandler(AddressOf btn1_Click)
Me.Controls.Add(btn1)

And then you create the sub that manages the event:

Friend Sub btn1_Click(sender As Object, e As EventArgs)
    'Write code here.
End Sub
Sign up to request clarification or add additional context in comments.

Comments

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.