首页 > 解决方案 > 如何在运行时动态创建多个控件

问题描述

我正在尝试在运行时向用户表单添加多个标签

这是棋盘游戏的玩家姓名;在游戏开始之前,玩家人数是未知的。我已经设法自己弄清楚如何使用动态数组函数来创建玩家列表。我使用了 For.....Next 循环来添加播放器名称。我以为我可以这样做以将标签添加到表单中,但它只添加了一个。根据声明新控件类型的位置,它要么只添加第一个玩家,要么添加最后一个玩家

此代码仅在组框内生成一个标签,即最后一个玩家

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Players_Num As Integer = InputBox("Enter the number of players")
        Dim Players(Players_Num) As String
        Dim newText As New Label

        For i = 0 To Players_Num - 1
            Players(i) = InputBox("Enter player name")
        Next

        'This piece of code was jsut for me to test that I was successfully using a For...Loop
        'to add the players names, and will be deleted later on
        For x = 0 To Players_Num - 1
            MessageBox.Show(Players(x))
        Next

        For z = 0 To Players_Num - 1
            newText.Name = "txt" & Players(z)
            newText.Text = Players(z)
            newText.Size = New Size(170, 20)
            newText.Location = New Point(12 + 5, 12 + 5)
            GroupBox1.Controls.Add(newText)
        Next
    End Sub
End Class

这个只放置第一个玩家

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Players_Num As Integer = InputBox("Enter the number of players")
        Dim Players(Players_Num) As String

        For i = 0 To Players_Num - 1
            Players(i) = InputBox("Enter player name")
        Next

        'This piece of code was jsut for me to test that I was successfully using a For...Loop
        'to add the players names, and will be deleted later on
        For x = 0 To Players_Num - 1
            MessageBox.Show(Players(x))
        Next

        For z = 0 To Players_Num - 1
            Dim newText As New Label
            newText.Name = "txt" & Players(z)
            newText.Text = Players(z)
            newText.Size = New Size(170, 20)
            newText.Location = New Point(12 + 5, 12 + 5)
            GroupBox1.Controls.Add(newText)
        Next
    End Sub
End Class

我在 vs 2015 和 2019 社区中尝试过这个

它哪里出错了?

标签: vb.netvisual-studio-2015visual-studio-2019

解决方案


从代码的外观来看,您正确地创建了控件,但它们的位置对于所有控件都是相同的,本质上,它们被放置在另一个顶部,第一个与第二个一起隐藏,后者与第三。

线

newText.Location = New Point(12 + 5, 12 + 5)

需要修改以将标签放置在不同的位置。

也许,像:

newText.Location = New Point(12 + 5, 12 + (z * 25))

这将使标签垂直对齐,它们之间的间隙为 25


推荐阅读