Search code examples
c#asp.netdynamicfindcontrol

find dynamically added controls from container


I am generating dynamic textbox controls on drop down selected index change event.

  protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (Attributes attribute in getAllAttributes(Convert.ToInt32(ddlCategories.SelectedValue)))
        {
            Panel div = new Panel();

            div.Attributes.Add("class", "form-group");
            HtmlGenericControl lbl = new HtmlGenericControl("label");

            lbl.Attributes.Add("class", "col-lg-2 control-label");
            lbl.InnerText = attribute.Name;

            Panel innerdiv = new Panel();
            innerdiv.Attributes.Add("class", "col-lg-10");

            TextBox txt = new TextBox();
            txt.ID = attribute.ID.ToString();
            txt.Attributes.Add("class", "form-control");
            innerdiv.Controls.Add(txt);

            div.Controls.Add(lbl);
            div.Controls.Add(innerdiv);
            CustomAttributes.Controls.Add(div);

        }
    }

Now after the user fill up the values in the form i want to get the values of the dynamically generated controls. But CustomAttributes.findControls("") doesn't work for me. it gives null all the time.

I also tried

var textBoxesInContainer = CustomAttributes.Controls.OfType<TextBox>();

but it also doesnt work.

Can any one please tell me what is going wrong here.

Thanks


Solution

  • Finally i found the reason after googling the issue. The issue in this question is a view state.

    In asp.net when the page post back it loses the viewstate for the dynamically generated controls. So to get over this issue i recreated the controls in the page load event when it is post back. in that way controls will be added back to the current page and i can find those controls in the button on click event.

    thanks all for your time and guidence.