2

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)
{
    if(Ispostback)
    {
        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 = 
                  (ContentPlaceHolder)this.Master.FindControl("MainContent");
        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;        
}
Liam
  • 27,717
  • 28
  • 128
  • 190
user575219
  • 2,346
  • 15
  • 54
  • 105
  • 5
    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. – M.Babcock Feb 01 '12 at 04:16
  • Possible duplicate of [ASP.NET Custom user control to add dynamically](https://stackoverflow.com/questions/2275625/asp-net-custom-user-control-to-add-dynamically) – Liam Mar 13 '19 at 09:05

3 Answers3

2

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 method.

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

Hope this works for you.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
0

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

rofans91
  • 2,970
  • 11
  • 45
  • 60
0
  1. move that code to OnInit (Page_Init)
  2. remove if(Ispostback) check when adding controls to control tree. Almost never you need to mind the postback state when adding controls dynamically.