Search code examples
c#lookuppropertygrid

How to implement a lookup value in property grid property


Using C#, Winforms, PropertyGrid.

Lets say I have the following class:

public class SomeClass
{
   public int Key;
   public Guid LookupKey;
}


//This class is a lookup class
public class Lookup
{
  public Guid Key;
  public string Description;
}

e.g. Data for lookup table

Key                  Description   
[SomeGuidValue1]     Value1  
[SomeGuidValue2]     Value2


SomeClass.LookupKey = Lookup.Key 

Now.. I already have the UIEditor showing a DataGridView containing the values for the Lookup table. But in the propertygrid.. I have the Guid value displaying instead of the description. How can I show the description whilst maintaining the Guid (Key) in the propertygrid property? i.e. I want to display Value1 instead of [SomeGuidValue1] but it should keep the reference to [SomeGuidValue1]?


Solution

  • You can create a TypeConverter, something like this:

    public class SomeClass
    {
        public int Key { get; set; }
    
        [TypeConverter(typeof(LookupConverter))]
        public Guid LookupKey { get; set; }
    }
    
    public class LookupConverter : TypeConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string)) //property grid will ask for this
            {
                var key = (Guid)value;
                return ConvertGuidToDescription(...) // TODO: implement this
            }
    
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }