标签:
Question: I‘m developing a C# component, I want to prevent the user from adding this component to the Form if the Form already has an instance of the component.
[Designer(typeof(myComponentDesigner))] class myComponent : Component { public myComponent(IContainer container) { // Add object to container‘s list so that // we get notified when the container goes away container.Add(this); } } class myComponentDesigner : ComponentDesigner { public override void InitializeNewComponent(System.Collections.IDictionary defaultValues) { IDesignerHost service = this.GetService(typeof(IDesignerHost)) as IDesignerHost; if (service == null) return; ComponentCollection cc = service.Container.Components; int count = 0; foreach (Component c in cc) { if (c.GetType() == this.Component.GetType() ) { count++; if (count > 1) { service.Container.Remove(this.Component); MessageBox.Show( "You cannot add more than one instance of the myComponet!"); return; } } } base.InitializeNewComponent(defaultValues); } }
Prevent Adding Component More than once
标签:
原文地址:http://www.cnblogs.com/eastson/p/4273953.html