views:

290

answers:

3

I've got a WebControl that I want to dynamically add a HiddenField from.

I've tried the following example: Click here, but that doesn't work due to the fact this.Page.Form is null in the Page Init event.

I've tried the following, but the value is never maintained:

HiddenField hd_IsDirty = new HiddenField();

protected override void OnInit(EventArgs e)
{

    this.Controls.Add(hd_IsDirty);
    hd_IsDirty.ID = "hd_IsDirty";

    base.OnInit(e);

}
A: 

See this answer on this question.

The answer will show you how to add a control dynamically, which is what you are trying to do.

David Basarab
Is there no 'magic' way of just adding the control and forgetting about it without using any aspx markup? I don't like the idea of using ViewState as it can be turned on and off.
GenericTypeTea
Not in ASP.NET it is not like windows, it does not keep it state.
David Basarab
I know. I was hoping there was a better method I didn't know about. I'll use my answer as it cannot be disabled like ViewState.
GenericTypeTea
A: 

The following works:

Create the control every time (seems bad!):

HiddenField hd_IsDirty = new HiddenField();

Tell the Page that the control requires a ControlState OnInit:

    this.Page.RegisterRequiresControlState(this);

Override the ControlState methods:

protected override object SaveControlState()
{

    object obj = base.SaveControlState();

    if (!string.IsNullOrEmpty(hd_IsDirty.Value))
    {
        if (obj != null)
        {
            return new Pair(obj, hd_IsDirty.Value);
        }
        else
        {
            return hd_IsDirty.Value;
        }
    }
    else
    {
        return obj;
    }
}

protected override void LoadControlState(object state)
{
    if (state != null)
    {
        Pair p = state as Pair;
        if (p != null)
        {
            base.LoadControlState(p.First);
            hd_IsDirty.Value = (string)p.Second;
        }
        else
        {
            if (state is string)
            {
                hd_IsDirty.Value = (string)state;
            }
            else
            {
                base.LoadControlState(state);
            }
        }
    }
}
GenericTypeTea
A: 

Theres always the dynamic controls placeholder at - http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx