title: ASP.NET Dropdown List in Codebehind vs in ASPX page
body: <p>I am generating a dropdown list in codebehind and cannot get the selectedindexchanged event to fire automatically.  It works fine when put directly into the ASPX page, but I need it to be in the codebehind.</p>
  
  <p>This doesn't work:</p>
  
  <pre><code>var deptList = new DropDownList
      {
          ID = "deptList",
          DataSource = departments,
          DataTextField = "deptname",
          DataValueField = "deptid",
          AutoPostBack = true,
          EnableViewState = true
      };
  
  deptList.SelectedIndexChanged += new EventHandler(deptList_SelectedIndexChanged);
  deptList.DataSource = departments;
  deptList.DataTextField = "deptname";
  deptList.DataValueField = "deptid";
  
  if (!IsPostBack)
      deptList.DataBind();
  
  deptList.Items.Insert(0, new ListItem("---Select Department---", string.Empty));
  
  writer.Write("Select a department: ");
  deptList.RenderControl(writer);
  </code></pre>
  
  <p>but this works: </p>
  
  <pre><code>&lt;asp:DropDownList ID="deptList" AutoPostBack="true" runat="server" OnSelectedIndexChanged="deptList_SelectedIndexChanged"&gt;&lt;/asp:DropDownList&gt;
  </code></pre>