ASP.NET页面中的Codebehind vs ASP.NET下拉列表 [英] ASP.NET Dropdown List in Codebehind vs in ASPX page

查看:144
本文介绍了ASP.NET页面中的Codebehind vs ASP.NET下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在codebehind中生成一个下拉列表,无法将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(选择部门:);
deptList.RenderControl(writer);

但这样做:

 < asp:DropDownList ID =deptListAutoPostBack =truerunat =serverOnSelectedIndexChanged =deptList_SelectedIndexChanged>< / asp:DropDownList> 


解决方案

如果您不添加控件足够早到页面控件需要在页面生命周期的早期添加,以便将事件绑定在一起。



您可能在Load事件中执行此操作太晚了。尝试在Init事件期间添加它或覆盖CreateChildControls方法。



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

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>

解决方案

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.

这篇关于ASP.NET页面中的Codebehind vs ASP.NET下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆