user2581791 user2581791 - 5 months ago 7
Vb.net Question

How to make a Label using only code?

I want to add a label to a form with the click of a button. When I use the code here it only adds 1 label, but I want to add an unlimited amount. Every time I click the button it only adds 1 label even if I change the name.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim lbl As New label
lbl.Size = New System.Drawing.Size(159, 23) 'set your size
lbl.Location = New System.Drawing.Point(12, 180) 'set your location
lbl.Text = (TextBox1.Text) 'set your name
Me.Controls.Add(lbl) 'add your new control to your forms control collection

End Sub

Answer

Something like this:

Dim lbl As New label
lbl.Size = New System.Drawing.Size(159, 23) 'set your size (if required)
lbl.Location = New System.Drawing.Point(12, 180) 'set your location
lbl.Text = "label text goes here" 'set the text for your label
Me.Controls.Add(lbl)  'add your new control to your forms control collection

I'll leave you to programatically set the location. You could use something like a global variable to keep count of how many labels have been created...