Click here to Skip to main content
15,909,645 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello Masters,

How are you all doing? I just have a question.

I am building this simple quiz application using asp.net/vb.net and sql server for the database. Now what I want to happen is that when I click on submit button, it will count all the correct answers of the user based on the radio button he clicks.

I have two radio buttons and the correct answer for those two radio buttons is A, now if they click both A for those 2 radio buttons, they will get a score of two else if wrong, it won't count the incorrect answer.

Here is what I got: (I am very sorry for the messy code, I am new to loops)
VB
Dim score As Integer = 0

     If RbAnswers1.SelectedValue = "A" Then

         For score = 0 To lbCorrectAnswerCount.Text.Count - 1

             score += 1

         Next score
         If RbAnswers2.SelectedValue = "A" Then
         Else
             lbCorrectAnswerCount.Text = score
             Exit Sub
         End If
     Else
         Exit Sub
         lbCorrectAnswerCount.Text = score

     End If

     lbCorrectAnswerCount.Text = score

Thank you in advance for your help.
Posted
Updated 9-Dec-14 1:18am
v2

The for loop you've got there doesn't make much sense. The point of loops is to do the same task repeatedly, In your case the repetitive task is checking the answer against the expected result. This needs to be the body of the loop. Try something like this:
VB
Dim answers = {RdAnswer1, RdAnswer2}
Dim expected = {"A", "A"}
Dim score As Integer = 0

For i As Integer = 0 To answers.Length - 1
  If answers(i).SelectedValue = expected(i) Then
  	score += 1
  End If
Next

We store answers and expected results as arrays. Then we loop trough them and if we find a match we update the score.
 
Share this answer
 
Hi Tomas Takac,

You are an angel! Thank you so much. Below is my code just in case beginners bump into the same issue as well:

VB
Dim answers(2) As String

answers(0) = RbAnswers1.SelectedValue
answers(1) = RbAnswers2.SelectedValue
answers(2) = RbAnswers3.SelectedValue


Dim CorrectAnswer(2) As String
CorrectAnswer(0) = "A"
CorrectAnswer(1) = "A"
CorrectAnswer(2) = "A"

Dim score As Integer = 0

For i As Integer = 0 To answers.Length - 1
    If answers(i) = CorrectAnswer(i) Then
        score += 1
    End If
Next
lbCorrectAnswerCount.Text = score
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900