Rogue Lotus 4
Rogue Lotus 4

Reputation: 39

How do I dynamically add labels one at a time?

Noob programmer here, go easy on me as I have zero idea of what I'm supposed to do, or what I'm doing. But here's what I want to do:

So I have a button in my project (ok, it's not a button, it's a label with a click event), and what I want it to do is that every time I press it, a new label appears, and if I press it again, another different label appears below it (specifically 50 pixels below it). I have managed to make it to the point where I can add another label, but I have no clue as to how I can make the same button add another one.

I have tried loops before, but for all I've done it only manages to make multiple labels at once, and not make it so that it only adds another label when I click the button. So here's my code:

 Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
        Dim xpoint As Integer
        Dim ypoint As Integer
        xpoint = 12
        ypoint = 200

        Dim label As New Label With {
            .Name = "test",
            .Location = New Point(xpoint, ypoint),
            .Font = New Font("Myriad Pro", 15),
            .Text = "bruh",
            .ForeColor = Color.White,
            .BackColor = Color.Black,
            .AutoSize = True
            }
        PictureBox1.Controls.Add(label)

Upvotes: 1

Views: 207

Answers (1)

Sebastian Brosch
Sebastian Brosch

Reputation: 43604

Your current solution is just stacking all the labels, so you can't see the different labels. You have to add the offset of each label like the following:

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
    Dim xpoint As Integer
    Dim ypoint As Integer
    Dim cntLabels As Integer = PictureBox1.Controls.Count
    xpoint = 12
    ypoint = 200 + (cntLabels * 50)

    Dim label As New Label With {
        .Name = "test",
        .Location = New Point(xpoint, ypoint),
        .Font = New Font("Myriad Pro", 15),
        .Text = "bruh",
        .ForeColor = Color.White,
        .BackColor = Color.Black,
        .AutoSize = True
        }
    PictureBox1.Controls.Add(label)
End Sub

Upvotes: 2

Related Questions