Use a type converter with a PropertyGrid control in C#

example

This example shows how you can use a type converter with a PropertyGrid control to let it display and edit compound properties.

The example Use a PropertyGrid to let the user edit objects in C# shows how to use the PropertyGrid control to display and edit object properties. However, if a property is an object itself, then the PropertyGrid displays whatever the object’s ToString method returns and doesn’t allow the user to edit it.

To let the PropertyGrid display and edit the value properly, you can provide a type converter class for that object type. This example uses a Person class that has a property named Address of type StreetAddress. The StreetAddress class has Street, City, State, and Zip properties.

To make a type converter, first decorate the class that you will convert (in this example, StreetAddress with the TypeConverter attribute defined in the System.ComponentModel namespace. This class uses the StreetAddressConverter class to convert StreetAddress objects to and from strings, so the StreetAddress class’s declaration looks like the following.

using System.ComponentModel;
...
[TypeConverter(typeof(StreetAddressConverter))]
class StreetAddress
{
    ...
}

Next make the type converter class. It should inherit from the TypeConverter base class, which is also defined in the System.ComponentModel namespace.

using System.ComponentModel;
...
class StreetAddressConverter : TypeConverter
{
    ...
}

This class should override several methods to give the PropertyGrid the tools it needs to display and edit properties of the type StreetAddress. These methods are:

Method Purpose
CanConvertFrom Returns true if the indicated type is string to indicate that the converter can create a StreetAddress from a string.
CanConvertTo Returns true if the indicated type is string to indicate that the converter can convert a StreetAddress into a string.
ConvertFrom Converts a string into a StreetAddress.
ConvertTo Converts a StreetAddress into a string.
GetProperties Returns a collection of type descriptors to tell the PropertyGrid about the properties that the StreetAddress supports.

To make converting a StreetAddress into a string easier, the StreetAddress class overrides its ToString method to return the object’s properties separated by commas. The following code shows the StreetAddress class’s ToString method.

// Return as a comma-delimited string.
public override string ToString()
{
    return Street + "," + City + "," + State + "," + Zip;
}

Two of the more interesting converter methods are ConvertTo and ConvertFrom. The following code shows the ConvertTo method, which converts a StreetAddress object into a string.

// Convert the StreetAddress to a string.
public override object ConvertTo(
    ITypeDescriptorContext context,
    System.Globalization.CultureInfo culture,
    object value, Type destinationType)
{
    if (destinationType == typeof(string)) return value.ToString();
    return base.ConvertTo(context, culture, value, destinationType);
}

If the destination type is string, this method simply calls the StreetAddress object’s ToString method and returns the result. If the destination type isn’t string, the method calls the TyepConverter base class’s ConvertTo method.

The following code shows the converter’s ConvertFrom method, which converts a string back onto a StreetAddress.

// Convert from a string.
public override object ConvertFrom(
    ITypeDescriptorContext context,
    System.Globalization.CultureInfo culture,
    object value)
{
    if (value.GetType() == typeof(string))
    {
        // Split the string separated by commas.
        string txt = (string)(value);
        string[] fields = txt.Split(new char[] {','});

        try
            {
                return new StreetAddress() {
                    Street=fields[0],
                    City=fields[1],
                    State=fields[2],
                    Zip=fields[3]
                };
            }
        catch
            {
                throw new InvalidCastException(
                    "Cannot convert the string '" +
                    value.ToString() + "' into a StreetAddress");
            }
        }
    else
    {
        return base.ConvertFrom(context, culture, value);
    }
}

This method splits the string into fields separated by commas. It then creates a new StreetAddress object, setting its properties to the field values.

The rest of the converter’s code is fairly straightforward but somewhat long, so it isn’t shown here. Download the example to see the whole thing.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in attributes, controls, OOP and tagged , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Use a type converter with a PropertyGrid control in C#

  1. Dennis says:

    Really great article!

    Excactly what I was looking for.

    Just a clear description of what to do when using property grids with own types.

    Thank you very much for sharing! ­čÖé

Leave a Reply

Your email address will not be published. Required fields are marked *