1

I have a parent control that has an instance of a HiddenField child control. I am using CreateChildControls() to add it. Everything works client side including the values being added to the field. However, on postback, the reference to the field is null

here is the code

    protected override void CreateChildControls()
    {
        assignedListField = new HiddenField();
        assignedListField.ID = ClientID + "_HiddenAssignedList";
        assignedListField.EnableViewState = true;

        Controls.Add(assignedListField);
        base.CreateChildControls();
    }

    public IList<DlpItem> GetAssignedItems()
    {
        //assignedListField = FindControl(ClientID + "_HiddenUnassignedList") as HiddenField;
        var TmpAssignedItems = new List<DlpItem>();
        var list = assignedListField.Value;
        var items = list.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var item in items)
        {
            var mix = item.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            var text = mix[0];
            var id = int.Parse(mix[1]);
            TmpAssignedItems.Add(new DlpItem(text, id));
        }
        return TmpAssignedItems;
    }

I have tried simply relying on the ViewState ... then also attempted using FindControl(). Neither works, it comes up as a null reference ... any input on what is going here?

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72

2 Answers2

3

As @Sebastian said, if you need to use any of the controls, they may be null because they are not available. However, you can call EnsureChildControls to create the control collection and ensure its there. This does not include the loading of ViewState.

However, you can't rely on viewstate if you are having client-side operations affect the data. What you need to do is have your control implement IPostBackDataHandler. In LostPostData, there you need to check for the hidden variable. Using postCollection[ClientID + "_HiddenAssignedList"], you can get the string value posted to the server, and process the results.

HTH.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • Silly mistake. I forgot to call EnsureChildControls() ... I thought I already had that in my code. Well that was the fix. Thanks =D – Matthew Cox Jan 10 '11 at 19:22
0

It is most likely that the CreateChildControls() has not yet been called when the ViewState is loaded (probably in your case ControlState is more usefull).

See http://msdn.microsoft.com/en-us/library/aa719775%28vs.71%29.aspx for the execution lifecycle.

You could store (and load) the state using the LoadViewState (SaveViewState)-method ( http://msdn.microsoft.com/de-de/library/system.web.ui.control.loadviewstate.aspx ) and store the values in fields 'till CreateChildControls() gets called.