ASP.NET页面中的Codebehind vs ASP.NET下拉列表 [英] ASP.NET Dropdown List in Codebehind vs in ASPX page
问题描述
这不起作用:
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屋!