FYI: Order is important in CreateChildControls

deepu

New Member
I had struggled with the following issue for a while and have received an answer from Microsoft (very quickly too!) I though you might appreciate the knowledge.<BR><BR>A ListBox control restores its Items list automatically on Post Back when that control is declared directly in the ASP.NET code. So you can write:<BR><script><BR>protected void Page_Load()<BR>{<BR> if (!IsPostBack)<BR> {<BR> MyList.Items.Add("Item1");<BR> MyList.Items.Add("Item2");<BR> }<BR>}<BR></script><BR><....HTML stuff...><BR><asp:ListBox id=MyList runat="server" /><BR><BR>Inside a Composite Control, you can do the same in the CreateChildControls method. However, there is an order to things. You must set any properties that are preserved by the control AFTER adding it to the parent's control list.<BR>This preserves the items in a list box:<BR>MyList = new ListBox()<BR>Controls.Add(MyList )<BR>MyList.Items.Add("Item1"); <BR>MyList.Items.Add("Item2");<BR>If you move Controls.Add(MyList) to the bottom, it does not preserve the items.<BR><BR>Unfortunately, the MSDN documentation has shown assigning of properties before the Controls.Add() call, at least in the primary example of Composite Controls: "Composite Server Control Sample".<BR><BR>--- Peter
 
Back
Top