1

I have dynamic drop down lists that are created based on what's selected in the list box.. When clicking confirm this is when the drop down lists are created. Clicking save is where I attempt to retrieve the values. However I am unable to retrieve that values that are in the drop down lists.

Code:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    int ID = 0;
    foreach (string value in values)
    {
        MyStaticValues.alEdit.Add(value);
        CreateEditForm(value, ID);
        ID += 1;
   }
   if (values.count != 0)
   {
        btnSave.Visible = true;
        btnConfirm.Enabled = false;
   }
}//End of btnConfirm_Click

protected void CreateEditForm(string Value, int ID)
{//Creates an edit form for the value inserted.
    string name = value;

    //This part adds a header
    phEditInventory.Controls.Add(new LiteralControl("<h2>" + name + "</h2>"));
    phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));

    //Create a label
    Label lblName = new Label();
    lblName.Text = "Name";
    lblName.ID = "lblName" + ID;
    lblName.CssClass = "control-label";

    //Create a Drop Down List
    DropDownList ddlName = new DropDownList();
    ddlName.ID = "ddlName" + ID;
    ddlName.CssClass = "form-control";

    //Set default N/A Values For Drop Down List
    ddlName.Items.Add(new ListItem("N/A", Convert.ToString("0")));

    //The Rest of the Values are populated with the database

    //Adds the controls to the placeholder
    phEditInventory.Controls.Add(lblName);
    phEditInventory.Controls.Add(ddlName);
    phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
} //End of CreateEditForm

protected void btnSave_Click(object sender, EventArgs e)
{
    string name = "";

    try
    {
        for (int i = 0; i < MyStaticValues.alEdit.Count; i++)
        {
            string nameID = "ddlName" + i.ToString();
            DropDownList ddlName = (DropDownList)phEditInventory.FindControl(nameID);
            name = ddlName.SelectedValue.ToString();
         }
     }
     catch (Exception ex)
     {
     }

     phEditInventory.Visible = false;
     btnSave.Visible = false;
     MyStaticValues.alEdit.Clear();
}//End of btnSave_Click Function
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467

1 Answers1

1

Your problem is that the dynamically created dropdown lists are not maintained on postback. When you click the Save button, a postback occurs, and the page is re-rendered without the dynamically created dropdowns. This link may help.

Maintain the state of dynamically added user control on postback?

Community
  • 1
  • 1
Marcie Kaiser
  • 186
  • 11