Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm aware this question has been asked many times before but I suspect I have a unique scenario.

I'm loading a Child Control (ASCX) and setting a Property on that Control. This works perfectly fine until postback where the property is null.

Herewith the First Class which loads the ChildControl :

protected override void CreateChildControls()
{
    MyUserControl control = (MyUserControl)Page.LoadControl(_ascxPath);
    control.MyProperty = base.MyProperty
    Controls.Add(control);
}

Then, on my Child Control I've got the following code:

public partial class MyUserControl : UserControl
{
    public MyType MyProperty { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Exception on next line because Property is null (only on postback)
        var somevalue = MyProperty.SubProperty;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
525 views
Welcome To Ask or Share your Answers For Others

1 Answer

Ok. Let me try to explain it.
1. Once page is created, you get full page lifecycle
2. You click on some control to create user control, and you get it
3. Now you are entering value to this control, and getting postback
4. On server side postback is handled, but as you can see viewstate actions appear as soon as page is loaded.
One of main purposes of viewstate is handling control events, to see if they are changed, or save their states or something else.
5. If on the moment, when viewstate is loaded you control is still not constructed, then all it's events and values would be ignored.

Solution either make it static control and just hide it, either create it before viewstate actions started.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...