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?
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.