加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:56:56 所属栏目:asp.Net 来源:网络整理
导读:我在代码隐藏中生成一个下拉列表,无法自动触发selectedindexchanged事件.它直接放入ASPX页面时工作正常,但我需要它在代码隐藏中. 这不起作用: var deptList = new DropDownList { ID = "deptList",DataSource = departments,DataTextField = "deptname",Dat
我在代码隐藏中生成一个下拉列表,无法自动触发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);

但这有效:

<asp:DropDownList ID="deptList" AutoPostBack="true" runat="server" OnSelectedIndexChanged="deptList_SelectedIndexChanged"></asp:DropDownList>

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读