1

I working with ASP.NET WebForms with C#. I have a button when clicking on it creates a dropdownlist. This list is created in the "createlist" method with parameters such as id and items. I also add a SelectedIndexChanged event handler.

The list is created successfully, but when I switch between the 3 options the handler is not firing, because the console never prints the message "CHANGE".

Here's my code:

namespace web
{
    public partial class Default : System.Web.UI.Page
    {
        List<string> lstDivs = new List<string>();

        protected void btn_Click(object sender, EventArgs e)
        {
            Control results = FindControl("results");
            lstDivs.Add("One");
            lstDivs.Add("Two");
            lstDivs.Add("Three");
            DropDownList lstTipo = createList("lstTipos", lstDivs);
            results.Controls.Add(lstTipo);
        }        

        public DropDownList createList(string id, List<string> lstStr)
        {
            DropDownList lst = new DropDownList();
            lst.Attributes.Add("runat", "server");
            lst.ID = id + "" + Variables.numDiv;
            lst.SelectedIndexChanged += new EventHandler(change);
            lst.AutoPostBack = true;

            lst.Items.Add(new ListItem("Select...", "Select..."));
            for (int i = 0; i < lstStr.Count; i++)
            {
                lst.Items.Add(new ListItem(lstStr[i], lstStr[i]));
                lst.Items[i].Attributes.Add("id", lst.ID + "" + i.ToString());
            }

            return lst;
        }

        protected void change(object sender, EventArgs e)
        {
            Debug.Write("CHANGE\r\n");
        }
    }
}
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
Paul9999
  • 751
  • 1
  • 11
  • 26

2 Answers2

2

Once a dynamic control is created and displayed to the user, it has to be recreated on a postback for its events to fire. Execution of events is triggered by the control itself, hence, if there is no control - there is nobody to detect the change and call your change method.

You have to persist the fact that the dropdown has been created (hidden field, ViewState, Session, database, ...) and create it again in Page_Load.

Igor
  • 15,833
  • 1
  • 27
  • 32
1

I'm not sure your control exists on the postback since it is dynamically created. I found this post which might be helpful: Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event

Also, I don't think you need to add the runat as an attribute. This should be done automatically.

Community
  • 1
  • 1