Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Dropdown List in Codebehind vs in ASPX page

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.

This doesn't work:

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);

but this works:

<asp:DropDownList ID="deptList" AutoPostBack="true" runat="server" OnSelectedIndexChanged="deptList_SelectedIndexChanged"></asp:DropDownList>
like image 597
Alex Avatar asked Dec 23 '22 05:12

Alex


1 Answers

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 probably doing it in the Load event, which is too late. Try adding it during the Init event or overriding the CreateChildControls method.

Edit: As Dave Swersky mentioned, make sure you do this on EVERY page request including postbacks.

like image 83
Mike Mooney Avatar answered Dec 29 '22 13:12

Mike Mooney