Search code examples
asp.netuser-controlslifecyclewizardradiobuttonlist

User controls on dynamic wizard steps


I am creating a wizard dynamically. The wizard is a quiz. The wizard is a user control (.ascx). On OnInit of the control I create steps and add them dynamically. On each step I have a user control (also .ascx) containing a radio button list. This user control is created based on a database setting. This all works fine. But, I would like the user to be able to go back and edit their quiz and I do not seem to be able to load up saved answers. What I had planned on doing was to create a BindAnswer method that retrieved the answer from the database and set the radio button list selected item in the usercontrol to reflect the answer. This BindAnswer method is getting the data from the database, and in the code behind it is setting the user control correctly. But, it does not render to the screen... I am assuming because I am not doing it in the right step of the life cycle.

Attempt 1:

public override void BindAnswer()
{
    IEnumerable<QuestionChoice> questionChoices;
    using (var questionChoiceService = new QuestionChoiceService())
    {
        questionChoices = questionChoiceService.GetQuestionChoicesByTestAndQuestion(Convert.ToInt32(Session["TestID"]), Question.ID);
    }
    if (questionChoices.Any())
    {
        foreach (var questionChoice in questionChoices)
        {
            if (RadioButtonList.Items.FindByValue(questionChoice.QuestionValueID.ToString()) != null)
            {
                RadioButtonList.Items.FindByValue(questionChoice.QuestionValueID.ToString()).Selected = true;
            }
        }
    }
}

And I call this like so:

QuizQuestionControlBase questionControl = null;
questionControl = (QuizQuestionControlBase)Page.LoadControl("~/UserControls/QuizQuestionRadioButton.ascx"); 
questionControl.BindData(pageId, question.ID);
questionControl.BindAnswer();     

var step = new WizardStep();
var userControl = (Control)questionControl;
step.Controls.Add(userControl); 

step.Title = String.Format("Step {0}", QuizWizard.WizardSteps.Count + 1);
QuizWizard.WizardSteps.Add(step);

And at this point I can step through code and see that the correct radio button is checked.

Attempt 2, instead of a separate BindAnswer method, I just set the radio button status on the RadioButtonList.OnDataBound event, but same results. It seems checked in code but does not render to the screen.


Solution

  • OK, found the answer. I need to bind the answers in OnLoad of the page that is hosting the wizard.