简体   繁体   中英

Selected Radio Buttons Error

I am developing a project that generates questions from a database, the questions are generated with multiple choice answers.

On this form I have got a textbox that reds the question from the database and 4 radio buttons that reads the possible answers from the database. The radio buttons text names are updated with records from a database table each time the "next button" is clicked.

What I want this program to do is that when the user selects one of the radio buttons, I want the system to check if the selected radio button textname equals the right answer in the database table. for example in the table there are 5 columns namely: option1, option2, option3, option4 and rightAnswer. So whenever a user selects a radio button, I would like the system to check if the selected radio button's textname equals the record in the "RightAnswer" column and if so I would a messagebox to show "correct" and if not the messgaebox to show "wrong"

WORK I HAVE DONE SO FAR:
This is the the way I am updating the radio button text names from the database.
This method is called when the form is loaded

void LoadingPossibleAnswers()
      {     
          Query = "SELECT * FROM AnswersTbl";
          theReader = conn.ExecuteStatement(Query);
          while (theReader.Read())
          {                      
                  radioButton1.Text = theReader["Option1"].ToString();
                  radioButton2.Text = theReader["Option2"].ToString();
                  radioButton3.Text = theReader["Option3"].ToString();
                  radioButton3.Text = theReader["Option4"].ToString();        
          }     
          conn.CloseConnection();
      }

This method is called when the button is clicked

void CorrectAnswer( RadioButton rdb)
{
    string correct = rdb.Text;

    Query = "SELECT * FROM FROM AnswersTbl;"
    theReader = conn.ExecuteStatement(Query);
    while (theReader.Read())
    {
        correct = theReader["RightAnswer"].ToString();

        if (rdb.Checked && rdb.Text == correct)
        {     
            MessageBox.Show("correct");
        }
        else
        {
            MessageBox.Show("wrong");
        }
    }
}

When ever I run my code above, else condition executes even if the correct radio button is selected. can anyone please help to why this is? am I missing out something?

As referring to your code, do this check ( rdb.Checked ) before entering to the CorrectAnswer method. Like

if(rdb.Checked)
{
CorrectAnswer(rdb);
}

Do this check for all RadioButton s and pass only the checked RadioButton to the method.

And you can remove rdb.Checked condition in side the CorrectAnswer method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM