Agregar dinámicamente una DropDownList

I am trying to add a dropdown dynamically. No errors except that I don't see the dropdown Here's the code:

protected void Page_Load(object sender, EventArgs e)
        DropDownList ddlPercent = new DropDownList();
        ddlPercent .ID = "ddlDiscountPercent";
        ddlPercent .AutoPostBack = true;
        Panel1.Controls.Add(ddlPercent );
        ddlPercent .ID = "ddlPercent " + 1;
        ddlPercent .Items.Add(new ListItem("5", "5%"));
        ddlPercent .Items.Add(new ListItem("10", "10%"));
        ddlPercent .Items.Add(new ListItem("15", "15%"));
        ddlPercent .Items.Add(new ListItem("20", "20%"));
        ddlPercent .Items.Add(new ListItem("30", "30%"));
        ddlPercent .Items.Add(new ListItem("50", "50%"));

        ddlPercent.SelectedIndexChanged += 
                  new EventHandler(ddlPercent_SelectedIndexChanged);

        ContentPlaceHolder cph = 
        cph.Controls.Add(ddlPercent );
        // ddlPercent.SelectedIndex =(Int32) ViewState["ddl_index"];

protected void ddlPercent_SelectedIndexChanged(object sender, EventArgs e)
     DropDownList ComboBox=(DropDownList)sender;
     ViewState["ddl_index"] = ComboBox.SelectedValue;        

preguntado el 01 de febrero de 12 a las 04:02

I understand this is a bad question but -3 without a single note to the OP asking them to fix their question (with detail of what you would want to fixed)... that's kind of ridiculous. -

3 Respuestas

The problem may be if you are not adding the control to the page early enough. Controls need to be added early in the page lifecycle to get their events tied in.

You're doing it in the Load event, which is too late. Try adding it during the Init event or overriding the CreateChildControls método.

And also make sure you do this on EVERY page request including postbacks.

Espero que esto funcione para usted.

Respondido 01 Feb 12, 08:02

It seems like because of the IsPostBack condition this code will only run if there page is reposted or have an event triggered.

Respondido 01 Feb 12, 08:02

  1. move that code to OnInit (Page_Init)
  2. remove if(Ispostback) check when adding controls to control tree. Almost nunca you need to mind the postback state when adding controls dynamically.

Respondido 01 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.