Often times, I have encounter questions regarding dynamically creating controls, specifically ones related to the ASP.NET AJAX Control Toolkit. Today, I was working with an application where I needed to create a dynamic  CalendarExtender and thought I would post the results.

Here is a simple example of how to create a dynamic CalendarExtender from code-behind:

// Create a textbox to hold the date
TextBox dateValue = new TextBox();
dateValue.ID = "dateValue";

// Create the calendar extender
AjaxControlToolkit.CalendarExtender ajaxCalendar =
    new AjaxControlToolkit.CalendarExtender();
ajaxCalendar.ID = "ajaxCalendar";
ajaxCalendar.Format = "MM/dd/yyyy";
ajaxCalendar.TargetControlID = dateValue.ID;

placeHolder1.Controls.Add(dateValue);
placeHolder1.Controls.Add(ajaxCalendar);

In the ASPX, I have just a simple PlaceHolder where I append the dynamically created controls:

<asp:placeholder id="placeHolder1" runat="server">
</asp:placeholder>

Finally, here’s the end result:

Calendar