Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I allow a user to add more than one type of object to a collection at design-time?

The default CollectionEditor will allow the user to add objects of type returned by your collection's indexer method.

You can make this CollectionEditor allow your user to pick the type of object to add by deriving from CollectionEditor and making the change as shown below. This will introduce a drop-down in the editor's "Add" button to allow the user to pick the type he wants to add.

using System.ComponentModel.Design;
using System.Drawing.Design;

public class Type1 {}
public class Type2 {}
public class Type3 {}

public class CustomCollectionEditor : CollectionEditor
{ 
  private Type[] types; 
  
  public CustomCollectionEditor(Type type) 
    : base(type) 
  { 
    types = new Type[] 
      { typeof( Type1 ), typeof( Type2 ), typeof( Type3 ) }; 
  } 

  // Return the types that you want to allow the user to add into your collection. 
  protected override Type[] CreateNewItemTypes() 
  { 
    return types; 
  } 
}

[ Editor( typeof( CustomCollectionEditor ), typeof( UITypeEditor ) ) ] 
public class CustomCollection : IList
{ 
  // ...
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter