Dynamically add CalendarExtender to Textbox subclass server control?

LockeCJ picture LockeCJ · Sep 17, 2008 · Viewed 11.4k times · Source

I'm trying to create a server control, which inherits from TextBox, that will automatically have a CalendarExtender attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.

Answer

Joseph Daigle picture Joseph Daigle · Sep 17, 2008

I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.

In the CreateChildControls method of the CompositeControl I use code similar to this:

TextBox textbox = new TextBox();
textbox.ID = this.ID + "Textbox";
textbox.Text = this.EditableField.TextValue;
textbox.TextChanged += new EventHandler(HandleTextboxTextChanged);
textbox.Width = new Unit(100, UnitType.Pixel);
CalendarExtender calExender = new CalendarExtender();
calExender.PopupButtonID = "Image1";
calExender.TargetControlID = textbox.ID;
this.Controls.Add(textbox);
this.Controls.Add(calExender);

Of course make sure that the form containing this CompositeControl has a toolkit script manager.