如何通过单击按钮使用vb代码制作标签

时间:2013-10-11 10:22:24

标签: vb.net

我想点击按钮向label添加form

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

谢谢大家。

 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

3 个答案:

答案 0 :(得分:0)

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

一种解决方案是使用可以调整Point的字段变量。

  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

答案 1 :(得分: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

答案 2 :(得分:0)

大家好,感谢大家的大力帮助,如果没有你使用我使用的代码,我就没那么远了

Public Class Form1     Dim counter As Integer = 1     Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)Handles 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

结束班