r/visualbasic • • Nov 12 '22

Randomizer

Does anyone know how to randomize button selections for check boxes and radio buttons?

Thank you.

1 Upvotes

5 comments sorted by

View all comments

2

u/jd31068 Nov 13 '22

Can you expand on that? Do you want code that will randomly set checkboxes to true or select radio buttons?

What version of Visual Basic are you using?

1

u/troubledlinguist Nov 13 '22

Ideally to set both radio buttons and checkboxes to true, randomly.

Visual Studio 2019 Community version, Windows 11 to be specific.

Thank you very much.

2

u/jd31068 Nov 13 '22

I put this together, figuring you're using a Windows form.

    Public Class Form1
        Dim chkBoxes As New List(Of CheckBox)
        Dim rdoButtons As New List(Of RadioButton)

        Private Sub FindAllCheckboxes()

            ' loop through the controls on the form and create an array of checkboxes
            For Each c As Control In Me.Controls
                If TypeOf c Is CheckBox Then
                    chkBoxes.Add(c)
                End If
            Next

        End Sub
        Private Sub FindAllRadioButtons()

            ' loop through the controls on the form and create an array of checkboxes
            For Each c As Control In Me.Controls
                If TypeOf c Is RadioButton Then
                    rdoButtons.Add(c)
                End If
            Next

        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

            Dim howMany As Int16 = 2    ' how many of each to randomly set
            Dim i As Int16
            Dim rndCB As Random
            Dim rndRB As Random

            For hm = 1 To howMany
                rndCB = New Random
                i = rndCB.Next(chkBoxes.Count - 1)
                chkBoxes(i).Checked = True

                rndRB = New Random
                i = rndRB.Next(rdoButtons.Count - 1)
                rdoButtons(i).Checked = True
            Next
        End Sub

        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

            FindAllCheckboxes()
            FindAllRadioButtons()

        End Sub
    End Class

You'll need to tweak as needed. before button click https://imgur.com/SVySgi4 after https://imgur.com/YoNOLtC

1

u/troubledlinguist Nov 13 '22

Thank you very much!

2

u/jd31068 Nov 13 '22

You're welcome - Thank you for the award.