Adding controls to WinForms form designer using code

Hi,

How can I create WinForms controls and inject them unto the design surface of the form designer via code. A demo program will be very much appreciated.

Thanks

I’ve got it working with the following:

var host = formDesignerControl1.DesignerHost;
var form = host.RootComponent as Form;
var button = (Button)host.CreateComponent(typeof(Button), "Button1");
button.Text = "Button1";
button.Parent = form;

Is this the recommended way or are there better ways?

Thanks

Yes, you are correct.

In case you may need it, below is an additional code snippet. It shows how to assign an auto-generated component name to the newly created component. Also it shows how to initialize it with a custom designer’s IComponentInitializer, if any.

private T AddNewComponent<T>(IDesignerHost host)
{
	var ncs = (INameCreationService)host.GetService(typeof(INameCreationService));
	var obj = (T)host.CreateComponent(typeof(T), ncs.CreateName(host.Container, typeof(T)));
	(host.GetDesigner((IComponent)obj) as IComponentInitializer)?.InitializeNewComponent(null);
	return obj;
}
1 Like