aBegginer aBegginer - 1 month ago 8
Vb.net Question

How to code a random button from an array?

I need to create a multiple choice question where the correct answer is displayed on one of four buttons (I don't know which one, as this will be generated randomly). The user then has to select the correct answer by pressing the button.

My problem is: how do I code the "If" statement, for when the button is pressed, when I don't know which button is the correct one?

This is the code

enter image description here

Answer Source

Try this:

Option Strict On
Public Class Form1
    Dim Answer As Integer
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Buttons() As Control = {Button1, Button2, Button3, Button4}
        Dim Rand As New Random()
        Dim Index As Integer = Rand.Next(0, Buttons.Length - 1)
        For i As Integer = 0 To 3
            Buttons(i).Text = CStr(Rand.Next(0, 100) * Rand.Next(0, 100))
        Next
        Answer = CInt(Label1.Text) * CInt(Label2.Text)
        Buttons(Index).Text = CStr(Answer)
    End Sub

    Sub CheckAnswer(ByVal Guess As Integer)
        If Guess = Answer Then
            MsgBox("Right!")
        Else
            MsgBox("Wrong!")
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click
        Dim objBtn As Button = DirectCast(sender, Button)
        CheckAnswer(CInt(objBtn.Text))
    End Sub
End Class