Retrieve value from dynamic dropdownlist in placeholder C#

时间:2015-06-30 13:27:09

标签: c# asp.net dynamic drop-down-menu webforms

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

1 个答案:

答案 0 :(得分:1)

您的问题是动态创建的下拉列表不会在回发时维护。单击“保存”按钮时,将发生回发,并且在没有动态创建的下拉列表的情况下重新呈现页面。这个链接可能有所帮助。

Maintain the state of dynamically added user control on postback?