Constructor in webform?

2019-04-12 02:58发布

问题:

I have an ASP.NET webform where I initialize an array with a list of controls on the page like this

FileUpload[4] = new FileUpload[4];
public myclass()
{
 fileUpload[0] = FileUpload1;
 fileUpload[0] = FileUpload2;
...etc
}

I then use these in the page load and they are all null. This seems a strange behavior to me. Can someone elaborate and explain? I can understand that they are null in the constructor but why should they be null when used in the page load.

回答1:

They are null because the controls haven't been created yet.

Take a look at the ASP.NET Page Life Cycle Overview and the Init event.



回答2:

If you want to add controls "manually", you need to do this in OnInit() so they can be given state from the LoadViewState() call that will happen just after OnInit().

If you don't know how many controls you need to add, because it's dynamic somehow, you can override LoadViewState and SaveViewState. See this example(written without Visual Studio):

public class MyPage : Page 
{
    class State
    {
        numberOfControls int
        otherState object
    }

    override void LoadViewState(savedState object)
    {
        var myState = (State)savedState;
        SetupMyControls(myState.numberOfControls);
        base.LoadViewState(myState.otherState);
    }

    override object SaveViewState()
    {
        return new State 
        {
            numberOfControls = GetNumberOfMyControls(),
            otherState = base.SaveViewState()
        };
    }
}