I have a piece of code in a User controls that normally should be put in the Page_Load (initializes other components such DropDowns etc.) but I need this to happen before the Page_Load of the page that hosts this control.
I tried to put this in Page_Init:
protected void Page_Init(object sender, EventArgs e) { if (!IsPostBack) { Methods.PopulateWhatList(cboWhatList0, cboWhatList1, fldWhat, Request['WhatId'], true); Methods.PopulateWhereList(cboWhereList0, cboWhereList1, fldWhere, Request['WhereId'], true); Methods.PopulateWhoList(cboWho, true, Request['WhoId']); Methods.PopulateWhenList(cboWhen, true, Request['WhenId']); Methods.PopulatePriceRangeList(cboPriceRange, true, Request['PriceRangeId']); } }
…but have experienced some problems. So where is the best place to but this type of code?
The problem I’m having (and might be unrelated) is that my:
protected override void Render(HtmlTextWriter writer) { Methods.EnableValidationWhereList(cboWhereList1, this.Page); Methods.EnableValidationWhatList(cboWhatList1, this.Page); base.Render(writer); }
Isn’t called on certain postbacks? (When pressing a LinkButton?)
I’ll try a wild guess to what you’re trying to do and suggest a solution:
In your
Page_Inityou’re populating the contents of various controls on the page. You’re dependent on URL parameters, hence theif(!IsPostBack)clause.After Page_Init, some of your controls are left in a disabled state, hence the need to enable them in your Render method.
When doing a postback on the LinkButton, you don’t see your dropdowns populated on the next page rendering.
What you’re experiencing is that disabled controls doesn’t get persisted to the ViewState. Since the SaveViewState is called before Render, you’re enabling the controls too late in the page lifecycle.
If you instead move your
Methods.EnableValidation...calls to a Pre_Render method on your page, control state will get persisted to the ViewState.After that fix, you should move your code in the Page_Init method to the Page_Load method, where it belongs. That way your controls data will have been loaded from the ViewState if you’re on a postback.