C# – Dynamically loaded Controls in a wizard

asp.netc

I've got the following code. I'm trying to create a wizard type of interface that dynamically loads user controls that dynamically load the controls for each step. Each step simply has a button that raises an event. The parent page is supposed to load up the next control in the wizard. What's happening is the same control is being rendered twice in a row, making me click the button twice.

I need another set of eyes to look at the code.

public partial class CreateTriviaGame : BasePage
    {
        private TriviaGame _game;
        private int _step = 1;

        protected void Page_PreLoad(object sender, EventArgs e)
        {
            LoadStepControl();
        }

        private void LoadStepControl()
        {           
            BaseTriviaGameControl ctrl = null;
            switch (_step)
            {
                case 1:
                    ctrl = (BaseTriviaGameControl)LoadControl("AddEditGame.ascx");
                    break;
                case 2:
                    ctrl = (BaseTriviaGameControl)LoadControl("CrudQuestions.ascx");
                    ctrl.TriviaGame = _game;
                    break;
                case 3:
                    ctrl = (BaseTriviaGameControl)LoadControl("AddEditPaymentInfo.ascx");
                    ctrl.TriviaGame = _game;
                    break;
                case 4:
                    ctrl = (BaseTriviaGameControl)LoadControl("ConfirmPayment.ascx");
                    ctrl.TriviaGame = _game;
                    break;
                case 5:
                    ctrl = (BaseTriviaGameControl)LoadControl("ThankForPayment.ascx");
                    ctrl.TriviaGame = _game;
                    break;
            }

            ctrl.EntitySaved += new EventHandler(ctrl_EntitySaved);
            holder1.Controls.Add(ctrl);

        }

        protected void ctrl_EntitySaved(object sender, EventArgs e)
        {
            _game = ((BaseTriviaGameControl)sender).TriviaGame;
            _step++;
            holder1.Controls.Clear();
            LoadStepControl();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            _game = (TriviaGame)ViewState["Game"];
            _step = (int)ViewState["Step"];
        }

        protected override object SaveViewState()
        {
            ViewState["Game"] = _game;
            ViewState["Step"] = _step;
            return base.SaveViewState();        
        } 


    }  

** EDIT **
I should add that the reason that I'm doing it like this is avoid having to declaratively add all of the controls to the page, then deal with each of them having loading before they need to be loaded.

Best Answer

Use Page_Init or Page_PreInit event.

Related Topic