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 the initialization object to set some initial values for the text field in PhoneInfo.
The user then changes these values and clicks the submit button on the page that connects to the submit_click event. This event calls the GetPhone () function in PhoneInfo. The return value has all new user-entered values, except that the phoneId value (stored in ViewState and NOT, edited by the user) is always returned as null.
I believe that viewstate is responsible for tracking user input via postback, so I cannot understand how user values are returned, not the explicitly set value of ViewState ["PhoneId"]! If I set the ViewState ["PhoneId"] value in the PhoneInfo page_load event, it will return it correctly after the postback, but this is not an option, because I can only initialize this value when the page is ready to provide it.
I am sure that I somehow ruined the page life cycle, any suggestion or questions would really help! I have included a significantly simplified version of the actual code below.
Contains page code
protected void Page_Load(object sender, EventArgs e)
{
Phone phone = controlToBind as Phone;
PhoneInfo phoneInfo = (PhoneInfo)LoadControl("phoneInfo.ascx");
phoneInfo.InitControl(phone);
Controls.Add(phoneInfo);
}
protected void submit_click(object sender, EventArgs e)
{
Phone phone = phoneInfo.GetPhone();
}
PhoneInfo.ascx codebehind
protected void Page_Load(object sender, EventArgs e)
{
}
public void InitControl(Phone phone)
{
if (phone != null)
{
ViewState["PhoneId"] = phone.Id;
txt_areaCode.Text = SafeConvert.ToString(phone.AreaCode);
txt_number.Text = SafeConvert.ToString(phone.Number);
ddl_type.SelectedValue = SafeConvert.ToString((int)phone.Type);
}
}
public Phone GetPhone()
{
Phone phone = new Phone();
if ((int)ViewState["PhoneId"] >= 0)
phone.Id = (int)ViewState["PhoneId"];
phone.AreaCode = SafeConvert.ToInt(txt_areaCode.Text);
phone.Number = SafeConvert.ToInt(txt_number.Text);
phone.Type = (PhoneType)Enum.ToObject(typeof(PhoneType), SafeConvert.ToInt(ddl_type.SelectedValue));
return phone;
}
}