Creating a custom type converter (C#) : TypeConverter « Custom Controls « ASP.NET Tutorial






using System;
using System.ComponentModel;
using System.Globalization;

public class Name
{
    private string _first;
    private string _last;

    public Name(string first, string last)
    {
        _first = first;
        _last = last;
    }

    public string First
    {
        get { return _first; }
        set { _first = value; }
    }
    public string Last
    {
        get { return _last; }
        set { _last = value; }
    }
}

public class NameConverter : TypeConverter
{

    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,
       CultureInfo culture, object value)
    {
        if (value is string)
        {
            string[] v = ((string)value).Split(new char[] { ' ' });
            return new Name(v[0], v[1]);
        }
        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context,
       CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            return ((Name)value).First + " " + ((Name)value).Last;
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}








14.17.TypeConverter
14.17.1.Applying the TypeConverter attribute to a property (C#)
14.17.2.Applying the TypeConverter attribute to a property (VB)
14.17.3.Creating a custom type converter (C#)
14.17.4.Creating a custom type converter (VB)