I am looking for a way (from my custom web control designer) to programmatically add (or remove) an ASP.NET control to a web form at design time.
I can use IDesignerHost.CreateComponent (or IDesignerHost.DestroyComponent) to add (or remove) a non-visual
component to the web form from my designer, but when I try to do it with a visual
control it adds the declaration to the code-behind page, but does not add the control to the .aspx page.
Am I doing something wrong or is there another way to do this? Here is a simple example that just tries to add a Label control when MyControl is added to a web form. Any help is much appreciated.
// MyControl.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace TestControls
{
[ToolboxData("<{0}:MyControl runat=server></{0}:MyControl>")]
[Designer(typeof(MyControlDesigner))]
public class MyControl : Label
{
}
public class MyControlDesigner : System.Web.UI.Design.WebControls.LabelDesigner
{
public override void Initialize(IComponent component)
{
base.Initialize(component);
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
if (host != null)
{
if (!host.Loading)
{
Label label = AddNewLabelComponent();
}
}
}
private Label AddNewLabelComponent()
{
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
Label label;
using (DesignerTransaction trans =
host.CreateTransaction("Creating new Label"))
{
label = (Label)host.CreateComponent(typeof(Label));
trans.Commit();
}
return(label);
}
}
}
Jim