Asp – Creating Dynamic controls based on the selected value of a static control

asp.net

I have a drop down list holding some choices. Based on user selection I need to create some dynamic controls and render them on the form.

My understanding is that dynamic controls need to be created in OnInit or in CreateChildControls so that the ViewState for these dynamic controls is restored correctly by the runtime.

The problem is, I am unable to get the SelectedValue of the dropdown in OnInit or CreateChildControls since the ViewState has not been restored for the dropdown as yet.

Is there any way to obtain the current selection so that I can create the dynamic controls based on the current user selection and add them the page correctly

EDIT:
The markup looks as follows:

<form id="form1" runat="server">
<div>
    <asp:DropDownList ID="ddl" runat="server" AutoPostBack="true"  AppendDataBoundItems="true">
        <asp:ListItem Text="(Select Color)" Value="" />
        <asp:ListItem Text="Red" Value="Red" />
        <asp:ListItem Text="Green" Value="Green" />
        <asp:ListItem Text="Blue" Value="Blue" />
    </asp:DropDownList>
    <asp:PlaceHolder ID="plHolder" runat="server" />
</div>
</form>

and here is the code behind:

 public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        TextBox tb = new TextBox();
        if (ddl.Text != "")
        {
            tb.Text = ddl.Text;
            if (Session["id"] != null)
            {
                string id = Session["id"].ToString();
                tb.ID = id;
            }
            else
            {
                Session["id"] = tb.ID = Guid.NewGuid().ToString().Replace("-", "");
            }
            plHolder.Controls.Add(tb);
        }

    }
}

On the line "tb.Text = ddl.Text;" I'm hoping to get the current selection and based on that set the value of the text property for the dynamic control. But the current selection has not been set yet since it's in OnInit.

Best Answer

If the controls really need to be created in OnInit or CreateChildControls then one thing you can do is get the value of your static control from the Request.Form[] collection during OnInit.

So instead of doing:

string selected = myDropDown.SelectedValue;

you do

string selected = Request.Form[myDropDownUniqueID];

... where myDropDownID is the 'unique id' assigned to myDropDown. Note that usually this will be the same as the 'id' assigned to the control, unless it is inside a control container.

This is effectively pulling the value straight out of the HTML Form data that gets sent to the server, rather than waiting for ASP.NET to unpack it into the properties of the control.