PropertyGrid: CheckBoxList Editor

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

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

Build the CheckBox List Editor

  1. public class CheckBoxListEditor : System.Drawing.Design.UITypeEditor
  2. {
  3.       private IWindowsFormsEditorService es = null;
  4.       
  5.       public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
  6.       {
  7.             return UITypeEditorEditStyle.DropDown;
  8.       }
  9.  
  10.       public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
  11.       {
  12.             if (provider != null)
  13.             {
  14.                   // This service is in charge of popping our ListBox.
  15.                   es = ((IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)));
  16.  
  17.                   if (es != null && value is CheckBoxList)
  18.                   {
  19.                         var property = (CheckBoxList)value;
  20.                         var cl = new CheckedListBox();
  21.                         cl.CheckOnClick = true;
  22.  
  23.                         Dictionary<String, Boolean> vals = new Dictionary<string, bool>();
  24.  
  25.                         foreach (KeyValuePair<String, Boolean> kvp in property.Values)
  26.                         {
  27.                               vals[kvp.Key] = kvp.Value;
  28.                               cl.Items.Add(kvp.Key, kvp.Value);
  29.                         }
  30.  
  31.                         // Drop the list control.
  32.                         es.DropDownControl(cl);
  33.  
  34.                         if (cl.SelectedItem != null )
  35.                         {
  36.                               vals[cl.SelectedItem.ToString()] = !vals[cl.SelectedItem.ToString()];
  37.                               property.Values = vals;
  38.                               property.SelectedItem = String.Join(", ", (from v in vals where v.Value == true select v.Key).ToList());
  39.                               value = property;
  40.                         }
  41.                   }
  42.             }
  43.  
  44.             return value;
  45.       }
  46. }
Series Navigation<< PropertyGrid: DropDown PropertyPropertyGrid: CheckBoxList Property >>