I’m working on a web based quiz system.
I have code that generates an ASP.NET table with a list of questions and radiobutton lists that indicate the answers for the quiz questions.
//Retrieve questions and answers - build the actual quiz
DataTable dtQuiz = qr.GetQuizQuestions(QuizID);
if (dtQuiz != null && dtQuiz.Rows.Count >= 1)
{
foreach (DataRow row in dtQuiz.Rows)
{
TableRow tr = new TableRow();
TableCell tcQuestionNum = new TableCell();
TableCell tcQuestion = new TableCell();
tcQuestionNum.VerticalAlign = VerticalAlign.Top;
tcQuestionNum.Controls.Add(new LiteralControl(row["QuestionNum"].ToString()));
tcQuestion.Controls.Add(new LiteralControl(row["Question"].ToString()));
RadioButtonList rblAnswers = qr.GetAnswers(QuizID, Int32.Parse(row["QuestionNum"].ToString()));
tcQuestion.Controls.Add(rblAnswers);
tr.Cells.Add(tcQuestionNum);
tr.Cells.Add(tcQuestion);
tblQuiz.Rows.Add(tr);
tblQuiz.DataBind();
}
}
This code generates the content just fine – the quiz questions appear, and the radiobutton lists render as expected.
There’s something weird when I have a separate button click event. After the user selects their answers, I want to do a postback and loop through the rows in the table, pulling the answers from the radiobutton list in the second cell of each row. I started down this path:
foreach (TableRow tr in tblQuiz.Rows)
{
TableCell tc = tr.Cells[1];
RadioButtonList rbl = (RadioButtonList) tc.Controls[1];
}
The problem is when the second button is clicked (to post the answers), the table has no rows. Why is this, and how can I correct this?
I can only think of one instance at this time, and that is that you have the code to create the table inside an
if (!IsPostBack){}(orIf (Not IsPostBack) Then ...if VB)If this is the case, your table won’t be created when you postback. You would need to put the code OUTSIDE of the
if (!IsPostBack){}so the table gets re-created when you postback.UPDATE
Based on your comment I would suggest:
Move the code that generates your table to a sub of its own. Something like (in vb)
Then when you click the button to generate the table, Call this sub.
Finally, when you click the button to submit the answers, call this sub again before processing any of the selections.
Ultimately, the table needs creating before you can process its contents.
don’t worry – the creation of the table won’t override any of the selections the user makes.