PropertyGrid: DropDown Editor

This entry is part 2 of 5 in the series C#: Property Grid
(Last Updated On: )

You may want to add a dropdown to your property grid. If you do then the below code is what you will need to create the editor.

Build the DropDown Editor

  1. public class DropDownEditor : System.Drawing.Design.UITypeEditor
  2. {
  3.       private IWindowsFormsEditorService es = null;
  4.       public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
  5.       {
  6.             return UITypeEditorEditStyle.DropDown;
  7.       }
  8.  
  9.       public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
  10.       {
  11.             if (provider != null)
  12.             {
  13.                   // This service is in charge of popping our ListBox.
  14.                   es = ((IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)));
  15.  
  16.                   if (es != null && value is DropDownList)
  17.                   {
  18.                         dynamic property = (DropDownList)value;
  19.                         var list = new ListBox();
  20.                         list.Click += ListBox_Click;
  21.  
  22.                         if (property.Values != null)
  23.                         {
  24.                               foreach (object item in property.Values)
  25.                               {
  26.                                     var propertyInfo = item.GetType().GetProperty(property.DisplayMember);
  27.                                     list.Items.Add(propertyInfo.GetValue(item, null));
  28.                               }
  29.                         }
  30.                         // Drop the list control.
  31.                         es.DropDownControl(list);
  32.  
  33.                         if (list.SelectedItem != null && list.SelectedIndices.Count == 1)
  34.                         {
  35.                               property.SelectedItem = list.SelectedItem;
  36.                               value = property;
  37.                         }
  38.                   }
  39.             }
  40.  
  41.             return value;
  42.       }
  43.  
  44.       void ListBox_Click(object sender, EventArgs e)
  45.       {
  46.             if (es != null)
  47.             {
  48.                   es.CloseDropDown();
  49.             }
  50.       }
  51. }
Series Navigation<< Dynamic Property GridPropertyGrid: DropDown Property >>