views:

336

answers:

3

On postback: How can I access ASP.NET controls in my code-behind file, which are added programmatically?

I am adding a CheckBox control to a Placeholder control:

PlaceHolder.Controls.Add(new CheckBox { ID = "findme" });

Controls added in the ASPX file are showing up fine in Request.Form.AllKeys except the ones I add programatically. What am I doing wrong?

Enabling the use of the ViewState on the controls does not help. If only it was that simple :)

A: 
CheckBox findme = PlaceHolder.FindControl("findme");

Is that what you mean?

Nick Spiers
Not exactly. I want to access the control on postback.
roosteronacid
+1  A: 

You should recreate your dynamic control on postback:

protected override void OnInit(EventArgs e)
{

    string dynamicControlId = "MyControl";

    TextBox textBox = new TextBox {ID = dynamicControlId};
    placeHolder.Controls.Add(textBox);
}
ika
Wouldn't this reset the state of the control?
roosteronacid
No, it wouldn't. To load state correctly the same ID of dynamic control is required - each time you recreate it.
ika
this was a lifesaver, thanks
dhulk
A: 

You will need to add the dynamically add the control during Page_Load to build the page up correctly each time. And then in your (i am assuming button click) you can use an extension method (if you are using 3.5) to find the dynamic control you added in the Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        PlaceHolder.Controls.Add(new CheckBox {ID = "findme"});
    }

    protected void Submit_OnClick(object sender, EventArgs e)
    {
        var checkBox = PlaceHolder.FindControlRecursive("findme") as CheckBox;
    }

Extension Method found here

public static class ControlExtensions
{
    /// <summary>
    /// recursively finds a child control of the specified parent.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    public static Control FindControlRecursive(this Control control, string id)
    {
        if (control == null) return null;
        //try to find the control at the current level
        Control ctrl = control.FindControl(id);

        if (ctrl == null)
        {
            //search the children
            foreach (Control child in control.Controls)
            {
                ctrl = FindControlRecursive(child, id);
                if (ctrl != null) break;
            }
        }
        return ctrl;
    }
}
Mark
Wouldn't this reset the state of the control?
roosteronacid
If the checkbox is ticked(true) on the webpage during the Page_Load it would be readded as false, however in the event handler for the Button Click it would have the correct value of ticked (true)
Mark