Accessing controls added programmatically on postback

限于喜欢 提交于 2019-11-29 12:11:06
ika

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);
}
CheckBox findme = PlaceHolder.FindControl("findme");

Is that what you mean?

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!