0

我想通过单击按钮添加label一个form

当我在这里使用该代码时,它只添加 1label但我想每次单击按钮时添加无限量;label即使我更改名称,它甚至会添加 1 。

谢谢大家。

 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
4

3 回答 3

0

正如@jlvaquero 正确指出的那样,您正在重叠标签。这样做的原因是您没有更改将这些标签添加到表单的点。

一种解决方案是具有可以调整点的字段变量。

  Private x As Integer = 12
  Private y As Integer = 180

 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(x, y) 'set your location
    lbl.Text = (TextBox1.Text) 'set your name
    Me.Controls.Add(lbl)  'add your new control to your forms control collection
    x += 10 'arbitrary value, you could adjust y, too
End Sub
于 2013-10-11T11:45:53.007 回答
0

只是对前两个非常好的答案的重新哈希。在这里,它试图说明至少必须根据用户提供的逻辑设置位置和文本

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

      ' YOU decide where EACH new label goes and pass the X,Y for each 
      ' new label; YOU decide on the text and pass it.  you can make them
      ' variables, but YOU have to do some of the thinking....

      ' <...> == information YOU provide
      Private x As integer = <where you want the new label>
      Private y as integer = <where you want the new label>
      Private txt as String = <Text for this new label>

      ' EXAMPLEs
      ' a) set text from a textbox
           ' txt = txtLblText.Text
      ' b) Set X position from another code integer variable
           ' x = thisX
      ' c) Set Y position from textbox input
           ' y = Integer.Parse(txtLblYPos.Text)

      Dim lbl as Label = MakeNewLabel(x, y, txt As string)

      Me.Controls.Add(lbl)  

End Sub


Friend function MakeNewLabel(x as integer, y as Integer, txt As String) as label
    Dim lbl As New label

    ' add other label props here as needed

    lbl.Size = New System.Drawing.Size(159, 23)       'set your size
    lbl.Location = New System.Drawing.Point(x, y)  'set your location
    lbl.Text = txt

    Return lbl
End Function
于 2013-10-11T12:01:51.570 回答
0

你好,谢谢大家的大力帮助,如果没有你,我不会走那么远,她是我使用的代码

公共类 Form1 Dim counter As Integer = 1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 处理 Button1.Click

    Dim lbl As New Label
    lbl.Name = "Label" & counter
    lbl.Size = New Size(150, 20)
    lbl.Location = New Point(200, counter * 22)
    lbl.Text = TextBox1.Text 'text on label
    Me.Controls.Add(lbl)
    counter += 1
End Sub

结束类

于 2013-10-11T13:47:15.443 回答