I have a page containing a control called PhoneInfo.ascx. PhoneInfo is dynamically created using LoadControl() and then the initControl() function is called passing in an i
Based on the comment responses, I'm adding another answer here that explains a part of the Page Lifecycle and what it means for post and viewstate data. Below is a more in-English (to a dev) and less about events version of the beginning of the page lifecycle:
So the problem here is that your dynamically-loaded control does not exist when post data is added to the page. When you add it, you put your default values in. ASP.NET no longer has a chance to populate it with the proper data.
I thought, like the answerers, that this problem existed because I was setting the ViewState variable too late to be saved during SaveViewState. However, I added an override for the SaveViewState event, and sure enough I was setting my ViewState variable long before the ViewState was saved. Too long before, it turns out.
Apparently after initialization, .net runs TrackViewState() which actually starts listening for any viewState variables you add. Since I had set this viewState value BEFORE TrackViewState() had run, everything appeared fine but the values were not actually being added during SaveViewState. I explicitly called TrackViewState() right before setting the variable and everything worked as expected.
My final solution was to assign a private property to hold the ID value through initialization and then to set the viewState variable during SaveViewState from the property value. This way I can ensure that TrackViewState has been run by .net without having to explicitly call it and mess up the flow of things. I reload the viewState value on page_load and use it to set the value of the property which I can then use in my GetPhone function.
This article talks about enableViewState.
private int _id = -1;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["PhoneId"] != null)
_id = SafeConvert.ToInt(ViewState["PhoneId"]);
}
protected override object SaveViewState()
{
ViewState["PhoneId"] = _id;
return base.SaveViewState();
}
public Phone GetPhone()
{
Phone phone = new Phone();
phone.Id = _id;
phone.AreaCode = SafeConvert.ToInt(txt_areaCode.Text);
phone.Number = SafeConvert.ToInt(txt_number.Text);
return phone;
}
ViewState is managed between the Init and Load events. You should utilize code in or functions called from the Page_Init handler instead of Page_Load when you are concerned with maintaining values from postbacks.
See this link for more information on the ASP.NET page life cycle.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
To do exactly what you're doing, you have to have the control loaded in the Init
portion of the page lifecycle.
However, to do it more easily, why don't you add it to an <asp:ContentPlaceHolder>
? I think it will make this much easier.