PropertyGrid Controls and Dropdowns

I wanted to create a drop-down list as an editor for the property; If there were only rows as entries in the drop-down list, this will work just fine (using StringConverter). However, when I tried to use a list of objects instead of strings, this would not work (note how this works for regular comboboxes!) This was my code:

public static List<Bar> barlist; public Form1() { InitializeComponent(); barlist = new List<Bar>(); for (int i = 1; i < 10; i++) { Bar bar = new Bar(); bar.barvalue = "BarObject " + i; barlist.Add(bar); comboBox1.Items.Add(bar); } Foo foo = new Foo(); foo.bar = new Bar(); propertyGrid1.SelectedObject = foo; } public class Foo { Bar mybar; [TypeConverter(typeof(BarConverter))] public Bar bar { get { return mybar; } set { mybar = value; } } } public class Bar { public String barvalue; public override String ToString() { return barvalue; } } class BarConverter : TypeConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(barlist); } } 

The result (embedded in the form, etc.) is as follows:

enter image description here

Clicking on the entry gave me this:

enter image description here

(Sorry for the German text, I'm not sure if I can change this, my VS is English, but my OS is not, error message

  Invalid property value. The object of type "System.String" cannot be converted to type "XMLTest.Form1+Bar". 

I am sure I can make a workaround for this by defining reverse conversion tools that convert the string back to a Bar object. This will require the keys to be different to ensure proper operation. Is there a better way to do this? Why is the comboBox built into the propertiesGrid control using Strings (a regular comboBox has no problem with this)

Also, can I programmatically reposition the middle separator? I have yet to find this option.

Thanks.

+7
source share
1 answer

I added the CanConvertFrom and ConvertFrom to your conversion class:

 class BarConverter : TypeConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(barlist); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { foreach (Bar b in barlist) { if (b.barvalue == (string)value) { return b; } } } return base.ConvertFrom(context, culture, value); } } 
+6
source

All Articles