Friday 2 April 2010

Dynamic User Controls – Part 2 – The Wrong Way

Following on from my session intro post, this post will deal with the “wrong” way to add controls to the page. Its wrong in the traditional sense, it just doesn’t provide as much control as you would like. Also it makes it difficult to manage the number of controls and events on the page. So lets get into it. Some prerequisites. I am using the AJAX Control Toolkit for my demos. Specifically I am using the AJAX Tab control to show off the demo. If you are not using one of the versions I uploaded, you will need this toolkit to follow the code I will be writing. Or you can just not use it and take out the tabContainer code :) Starting off, I have the standard Default.aspx page with a ScriptManager control on it. Also on the page I have an instance of the AJAX Control Toolkit TabControl. In the TabControl I have one tabPanel with an ASP PlaceHolder control and an ASP Button Control
<cc1:TabPanel ID="tabStart" runat="server" HeaderText="Start">
<asp:PlaceHolder ID="phControls" runat="server" />
<br />
<asp:Button ID="btnAddControl" runat="server" Text="Add a new text box"
CausesValidation="false" OnClick="AddDemoControl"/>

In the code behind of the page I have the Page_Load event and the event handler for the OnClick event of the ASP button.
protected void Page_Load(object sender, EventArgs e)
if (Page.IsPostBack) return;
//Add 2 new textboxes to the specified placeholder
phControls.Controls.Add(new TextBox());
phControls.Controls.Add(new TextBox());

protected void AddDemoControl(object sender, EventArgs e)
phControls.Controls.Add(new TextBox());

When the page is loaded for the first time, 2 textbox controls are added to the page. When you click the button, only one textbox is shown. This is because the check to see if the page is a postback stops the first two textboxes from being loaded. Removing this line will mean that when you click the button three textboxes are shown on screen.

If you keep clicking the button, only three textboxes will be shown. This is because the controls do not survive the postback event and so are recreated new every time. So in this way this is one of the reasons I will use the repeater model to create dynamic controls.

How to do this using a basic textbox control will be covered in the next post.

No comments: