Search code examples
c#winformspropertygridcollectioneditorcustom-collection

Is there a PropertyGrid Collection Editor "Add" button event or override?


Is there an event or a function that is triggered when the Windows Forms PropertyGrid Collection Editor "Add" button is clicked? (see image)

I'd like to add some custom code to run when this button is pressed.

I use a custom collection for a list of objects (CollectionBase). My constructor is called when the Add button is pressed, but I see no other functions in the call list where I could insert some custom code.

enter image description here


Solution

  • There is no documented way, you'll have to use your own editor. But you can derive from the standard editor class. Here is an example of such a hack:

    Define the custom editor attribute like this on the collection property:

    [Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]
    public List<Child> Children { get; }
    

    With this editor code:

    // CollectionEditor needs a reference to System.Design.dll
    public class MyCollectionEditor : CollectionEditor
    {
        public MyCollectionEditor(Type type)
            : base(type)
        {
        }
    
        protected override CollectionForm CreateCollectionForm()
        {
            CollectionForm form = base.CreateCollectionForm();
            var addButton = (ButtonBase)form.Controls.Find("addButton", true).First();
            addButton.Click += (sender, e) =>
                {
                    MessageBox.Show("hello world");
                };
            return form;
        }
    }
    

    The add button is a simple Winforms button, so you can do anything with it.