Codebehind中的ASP.NET下拉列表与ASPX页面中的相关联

Ale*_*lex 4 asp.net selectedindexchanged code-behind drop-down-menu

我在代码隐藏中生成一个下拉列表,无法自动触发selectedindexchanged事件.它直接放入ASPX页面时工作正常,但我需要它在代码隐藏中.

这不起作用:

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);
Run Code Online (Sandbox Code Playgroud)

但这有效:

<asp:DropDownList ID="deptList" AutoPostBack="true" runat="server" OnSelectedIndexChanged="deptList_SelectedIndexChanged"></asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

Mik*_*ney 7

问题可能在于您没有及早将控件添加到页面.需要在页面生命周期的早期添加控件以使其事件处于捆绑状态.

您可能在Load事件中执行此操作,为时已晚.尝试在Init事件期间添加它或覆盖CreateChildControls方法.

编辑:正如Dave Swersky所提到的,请确保在每个页面请求(包括回发)上执行此操作.