无法在VB.Net中生成多个单选按钮

时间:2018-06-25 15:36:59

标签: vb.net visual-studio radio-button dynamically-generated

我正在处理的程序的一部分将涉及为存储在数组中的每个条目制作多行单选按钮。这将涉及以编程方式创建每个都有三个单选按钮的组框。但是,我似乎无法让我的代码为每个框生成多个1个按钮。我的沙盒代码如下。

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim rb As RadioButton
    Dim gb As GroupBox

    For i As Integer = 1 To 3

        gb = New GroupBox

        With gb
            .Size = New System.Drawing.Size(400, 100)
            .Name = "gb" & i
            .Top = 30 + 100 * (i - 1)
            .Left = 30
        End With

        Me.Controls.Add(gb)

        For j As Integer = 1 To 3

            rb = New RadioButton

            With rb
                .Top = 50
                .Left = 40 * j
                .Name = "rb" & i & j
            End With

            Me.Controls("gb" & i).Controls.Add(rb)
        Next

    Next

    Form2.Show()

End Sub

值得一提的是:用“ TextBox”查找/替换“ RadioButton”给了我三个文本框-单选按钮是否缺少一些属性?

提前谢谢!

3 个答案:

答案 0 :(得分:0)

一旦定义width属性,就会显示复选框。

我发现至少我的计算机上的默认大小为104。因此,向右移动40并不足够。

            With rb
                .Top = 50
                .Left = 40 * j
                .Name = "rb" & i & j
                .BackColor = System.Drawing.Color.Orange
                '.Text = "rb" & i & j
                .Width = 40
            End With

背景色(可以删除,有助于显示复选框的实际位置)。

答案 1 :(得分:0)

您的单选按钮可能在那里,它们就在组框的后面。顶部和左侧是相对于父级的。

RadioButton1.Parent = GroupBox1
RadioButton1.Top = 30
RadioButton1.Left = 30
GroupBox1.Controls.Add(RadioButton1)

答案 2 :(得分:0)

显示的代码由于宽度而出现问题。不确定您要完成什么,但这会“修复”您的代码。

    Dim rb As RadioButton
    Dim gb As GroupBox

    For i As Integer = 1 To 3

        gb = New GroupBox

        With gb
            .Size = New System.Drawing.Size(400, 100)
            .Name = "gb" & i
            .Top = 30 + 100 * (i - 1)
            .Left = 30
            .Anchor = .Anchor Or AnchorStyles.Right
        End With

        Me.Controls.Add(gb)

        For j As Integer = 1 To 3

            rb = New RadioButton

            With rb
                .Top = 50
                .Left = 40 * j
                .Name = "rb" & i & j
                .AutoSize = True 'added <<<<<<<<<<<<<<<<<<<
                '.Text = .Name
                '.BackColor = Color.AliceBlue
            End With

            Me.Controls("gb" & i).Controls.Add(rb) 'note rb.Width changes here

            Debug.Write(rb.Name)
            Debug.WriteLine("  Top: {0}, Left: {1}, Width: {2}, Height: {3}",
                            rb.Top, rb.Left, rb.Width, rb.Height)

        Next

    Next