I’m making a basic multiple choice game. I have an existing database given the fields: Qno, Question, Correct, Wrong1, Wrong2, and Wrong3. When the form loads, this code generates a random order of question from my database placing the question on a label and the choices on respective button.
private void Form1_Load(object sender, EventArgs e)
{
NewQuestion();
public void NewQuestion()
{
Stack numberCheck = new Stack();
int y = 0;
Random x = new Random();
bool exists = false;
y = x.Next(1, 50);
exists = numberCheck.Contains(y);
while (exists == true)
{
y = x.Next(1, 50);
exists = numberCheck.Contains(y);
}
label2.Text = Convert.ToString(y);
da.SelectCommand = new SqlCommand("SELECT Question from MC WHERE QNo=@id", cs);
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = label2.Text;
cs.Open();
label1.Text = Convert.ToString(da.SelectCommand.ExecuteScalar());
cs.Close();
da.SelectCommand = new SqlCommand("SELECT Correct from MC WHERE QNo=@id", cs);
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = label2.Text;
cs.Open();
button2.Text = Convert.ToString(da.SelectCommand.ExecuteScalar());
cs.Close();
da.SelectCommand = new SqlCommand("SELECT Wrong1 from MC WHERE QNo=@id", cs);
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = label2.Text;
cs.Open();
button3.Text = Convert.ToString(da.SelectCommand.ExecuteScalar());
cs.Close();
da.SelectCommand = new SqlCommand("SELECT Wrong2 from MC WHERE QNo=@id", cs);
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = label2.Text;
cs.Open();
button4.Text = Convert.ToString(da.SelectCommand.ExecuteScalar());
cs.Close();
da.SelectCommand = new SqlCommand("SELECT Wrong3 from MC WHERE QNo=@id", cs);
da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = label2.Text;
cs.Open();
button5.Text = Convert.ToString(da.SelectCommand.ExecuteScalar());
cs.Close();
}
}
}
Problem list:
- The questions can be repeated
- The list of answers are in the same order as the way they are declared in the database wherein button 1 is always Correct, and the rest of the buttons are wrong
numberCheckis recreated every time you callNewQuestion. To have the it work correctly, you must move it out of the method and make it a class member.Look at Randomize a List<T> which contains a great shuffle method to randomize the order of the list of answers.
Even though promoting the
numberCheckvariable into a member will work it’s actually a bad solution. For the first few items it will work, but when you’v run through 49 questions it will continue to loop until it randomly happens to select the only question left. A much better alternative is to create an initial list of number 1-50 and then use the Shuffle method from the post linked in 2) to select the order. Then simply take the next item in that list when fetching a new question.