ASP.NET dropdown in Codebehind vs on ASPX page

I am generating a dropdown in codebehind and cannot automatically fire the selectedindexchanged event. It works great when directly entering an ASPX page, but I need it to be in code.

This does not 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 it works:

 <asp:DropDownList ID="deptList" AutoPostBack="true" runat="server" OnSelectedIndexChanged="deptList_SelectedIndexChanged"></asp:DropDownList> 
+4
source share
5 answers

The problem may be that you are not adding the control to the page early enough. Controls need to be added at an early stage in the page life cycle in order to link their events.

You are probably doing this 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 every time you request a page, including postback.

+6
source

You have a grid in your code. Try to separate creation, data binding and event calling.

Example:

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

Then in the code behind (Page_Load):

 deptList.SelectedIndexChanged += new EventHandler(deptList_SelectedIndexChanged); if (!IsPostBack) { deptList.DataTextField = "deptname"; deptList.DataValueField = "deptid"; deptList.DataSource = departments; deptList.DataBind(); deptList.Items.Insert(0, new ListItem("---Select Department---", string.Empty)); } 
+2
source

To clarify Mike Mooney's answer: you also need to make sure that you add the control back to the control tree with each postback. The control tree is recreated at each postback, read from the markup. If you add it programmatically and never again, there is no control in the tree to receive the event.

+2
source

It looks like you are not adding a control to the control collection. You must add the control to the control hierarchy and make sure that it is added at each postback to ensure that the control exists to receive the event. By adding a control, you do not need to access RenderControl directly.

0
source

The problem was that if AutoPostBack = true was not in the drop-down list, this would never call the function.

0
source

Source: https://habr.com/ru/post/1301585/


All Articles