Search code examples
vb.netvisual-studiobuttongroupbox

VB How do I dynamically create a groupbox to appear and group radiobuttons which are in an array?


I have an array of 2 RadioButtons. One displays the text "TRUE", the other "FALSE", and they appear when a user selects a TRUE/FALSE style question.

However, when multiple TRUE/FALSE style questions are selected, the RadioButtons all seem to be linked, rather than linked in the pairs which they appear in. E.g. if a 3 question quiz has 2 TRUE/FALSE style questions, then when you select an answer on one question, it removes the answer on the other TRUE/FALSE style question.

Code for reference: (inside a For loop (k) and inside a select case (when a truefalse style question is selected))

grpTrueFalse(k) = New GroupBox 
grpTrueFalse(k).Location = New Point((X - 10), (Y - 10))
grpTrueFalse(k).BackColor = Color.Transparent
grpTrueFalse(k).Visible = False
grpTrueFalse(k).Width = 250 : grpTrueFalse(k).Height = 50
frmQuizBuild.Controls.Add(grpTrueFalse(k))

rdbtrue(k) = New RadioButton : rdbtrue(k).Location = New Point((X + 120), Y)
rdbtrue(k).Text = "TRUE" : rdbtrue(k).Font = New Font("Arial", 15)
rdbtrue(k).BackColor = Color.Transparent
frmQuizBuild.Controls.Add(rdbtrue(k))

rdbfalse(k) = New RadioButton : rdbfalse(k).Location = New Point(X, Y)
rdbfalse(k).Text = "TRUE" : rdbfalse(k).Font = New Font("Arial", 15)
rdbfalse(k).BackColor = Color.Transparent
frmQuizBuild.Controls.Add(rdbfalse(k))

For the record the GroupBox appears on top of the RadioButtons and isn't really doing anything at the moment.


Solution

  • Your code needs to be something like:

    Dim arrRButton(1) As RadioButton
    arrRButton(0) = New RadioButton
    arrRButton(1) = New RadioButton
    
    Dim GroupBox1 As New GroupBox
     With GroupBox1
      .Controls.Add(rdbTrue(k))
      .Controls.Add(rdbFalse(k))
     End With
    

    You can also set the location by using a similar With block. (Eg; With arrRButton(0) Then .Location = x, .Text = x etc)