Question

I'm trying to make a property that will show a different text in its value input each time the user selected an item. But my problem with the values is that they're strings with underscores and lowercase first letters, for example: "naval_tech_school". So I need the ComboBox to display a different value text that will look like this "Naval Tech School" instead.

But the value should remain "naval_tech_school" if trying to access it.

Was it helpful?

Solution

If you just want to change the value (without a special editor) back and forth between the two formats, you just need a custom TypeConverter. Declare the property like this:

public class MyClass
{
    ...

    [TypeConverter(typeof(MyStringConverter))]
    public string MyProp { get; set; }

    ...
}

And here is a sample TypeConverter:

public class MyStringConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string svalue = value as string;
        if (svalue != null)
            return RemoveSpaceAndLowerFirst(svalue);

        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        string svalue = value as string;
        if (svalue != null)
            return RemoveUnderscoreAndUpperFirst(svalue);

        return base.ConvertTo(context, culture, value, destinationType);
    }

    private static string RemoveSpaceAndLowerFirst(string s)
    {
        // do your format conversion here
    }

    private static string RemoveUnderscoreAndUpperFirst(string s)
    {
        // do your format conversion here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top