Get reference to a dropdownbox with c# at Page PreRender
-
21-08-2019 - |
Question
I want to add options to a dropdownbox on my aspx page from the c# code behind during load. I don't know how to get a reference to the control. I have some c# code that is triggered when the user changes the dropdownbox. In that I get a reference to the dropdown with:
DropDownBox ddb = (DropDownBox)info.Toolbar.ToolbarItems.Find("ID");
But that won't work if I try it in
protected void Page_PreRender(object sender, EventArgs e)
{
on my aspx.cs
What am I missing? Thanks.
Solution
If you want the selected item of the dropdown to be automatically selected from viewstate on postbacks you will need to have all the items in the dropdown by the time Page_PreLoad fires. To do this you will want to put your code in Page_Init, at this point the controls are created but viewstate has not yet been injected into them.
Take a look here ASP.NET Page Life Cycle Overview for info on the page lifecycle.
I see that your dropdown is in a parent container, you may need to call info.EnsureChildControls() before you use Find() if it is not able to get a reference to your control.
OTHER TIPS
PreRender is toward the end of the page lifecycle. Are you sure you want to be making changes there? Sounds like you should be changing items in the dropdown when it is initially bound or when its selection is changed.
http://codebetter.com/blogs//images/codebetter_com/raymond.lewallen/89/o_aspNet_Page_LifeCycle.jpg