Search code examples
vb.netms-accessoledb

Randomize answers in RadioButtons through Access database


I'm currently working on my multiple-choice quiz and am having trouble with this section. I'm trying to get the answers from the database and have them randomly go into the radio buttons. So far I have each of them go into radio buttons but since I'm new to this, I'm unsure of how to randomize it.

Private Sub Answers()
    Dim dr As OleDbDataReader
    Dim cm As New OleDbCommand
    Dim cn As New OleDbConnection

    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=login.accdb"
    cn.Open()

    cm.CommandText = ("SELECT pAns1,pAns2,pAns3,CorrectAns FROM MCQ WHERE QuestionNumber = '" & n & "'")
    cm.Connection = cn
    dr = cm.ExecuteReader
    dr.Read()
    RadioButton1.Text = dr.Item("pAns1")
    RadioButton2.Text = dr.Item("pAns2")
    RadioButton3.Text = dr.Item("pAns3")
    RadioButton4.Text = dr.Item("CorrectAns")
End Sub

Solution

  • You can do something like:

    'A class level variable.
    Private ReadOnly rand As New Random
    
    Private Sub Answers()
        Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=login.accdb")
            Using cmd As New OleDbCommand("SELECT pAns1, pAns2, pAns3, CorrectAns FROM MCQ WHERE QuestionNumber = ?", cn)
                cmd.Parameters.AddWithValue("@QuestionNumber", n)
                cn.Open()
                Using r As OleDbDataReader = cmd.ExecuteReader
                    Dim arr = {
                            r.GetOrdinal("pAns1"),
                            r.GetOrdinal("pAns2"),
                            r.GetOrdinal("pAns3")
                        }.OrderBy(Function(x) rand.Next).ToArray
                    If r.Read Then
                        RadioButton1.Text = r.Item(arr(0)).ToString
                        RadioButton2.Text = r.Item(arr(1)).ToString
                        RadioButton3.Text = r.Item(arr(2)).ToString
                    End If
                End Using
            End Using
        End Using
    End Sub
    

    Please note:

    • The snippet respects the mentioned above comments.

    • You should close the connection and dispose the disposable objects. The Using ... End Using block will do that for you.

    • For the randomize requirement, we get the columns ordinals to create an array of integers and shuffle the contents. You might want to read this post for different arrays shuffling ways.