Type Converter Example

This example shows how to create a type converter named AuthorConverter, whichis used with the Author object from other control authoring examples. ASP.NET uses type converters at run time to serialize and deserialize objects stored in control state and in view state. The AuthorConverter example converts an Author object to a String and a String representation to an Author object. The Author type is described in Server Control Properties Example.

You associate a type converter with a type (or with a property of the type for which the converter is defined) using the TypeConverterAttribute. AuthorConverter allows the Book control to store the Author property in view state. A custom type can be stored in view state only if it has a type converter defined for it and associated with the type.

The AuthorConverter class derives from ExpandableObjectConverter so that the property browser in a visual designer can provide an expand/collapse user interface for editing the subproperties of the Author type.

Code Listing for the AuthorConverter Class

' AuthorConverter.vbImports System
Imports System.ComponentModel
Imports System.ComponentModel.Design.Serialization
Imports System.Globalization
Imports System.Reflection

Namespace Samples.AspNet.VB.Controls
    PublicClass AuthorConverter
        Inherits ExpandableObjectConverter

        PublicOverridesFunction CanConvertFrom( _
        ByVal context As ITypeDescriptorContext, _
            ByVal sourceType As Type) AsBooleanIf sourceType IsGetType(String) ThenReturnTrueEndIfReturnMyBase.CanConvertFrom(context, sourceType)
        EndFunctionPublicOverridesFunction CanConvertTo( _
        ByVal context As ITypeDescriptorContext, _
            ByVal destinationType As Type) AsBooleanIf destinationType IsGetType(String) ThenReturnTrueEndIfReturnMyBase.CanConvertTo(context, destinationType)
        EndFunctionPublicOverridesFunction ConvertFrom( _
        ByVal context As ITypeDescriptorContext, _
        ByVal culture As CultureInfo, ByVal value AsObject) AsObjectIf value IsNothingThenReturnNew Author()
            EndIfIf (TypeOf value IsString) ThenDim s AsString = CStr(value)
                If s.Length = 0 ThenReturnNew Author()
                EndIfDim parts() AsString = s.Split(" ".ToCharArray)

                ' Determine if name is stored as first and last,                 ' first, middle, and last,                ' or is in error.If (parts.Length < 2) Or (parts.Length > 3) ThenThrowNew ArgumentException( _
                        "Name must have 2 or 3 parts.", "value")
                EndIfIf parts.Length = 2 ThenReturnNew Author(parts(0), parts(1))
                EndIfIf parts.Length = 3 ThenReturnNew Author(parts(0), parts(1), parts(2))
                EndIfEndIfReturnMyBase.ConvertFrom(context, culture, value)
        EndFunctionPublicOverridesFunction ConvertTo( _
            ByVal context As ITypeDescriptorContext, _
        ByVal culture As CultureInfo, ByVal value AsObject, _
        ByVal destinationType As Type) AsObjectIf value IsNotNothingThenIfNot (TypeOf value Is Author) ThenThrowNew ArgumentException("Invalid Author", _
                        "value")
                EndIfEndIfIf destinationType IsGetType(String) ThenIf value IsNothingThenReturnString.Empty
                EndIfDim auth As Author = CType(value, Author)

                If auth.MiddleName <> String.Empty ThenReturnString.Format("{0} {1} {2}", _
                    auth.FirstName, _
                    auth.MiddleName, _
                    auth.LastName)
                ElseReturnString.Format("{0} {1}", _
                         auth.FirstName, _
                        auth.LastName)
                EndIfEndIfReturnMyBase.ConvertTo(context, culture, value, _
                destinationType)
        EndFunctionEndClassEndNamespace
// AuthorConverter.csusing System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;

namespace Samples.AspNet.CS.Controls
{
    publicclass AuthorConverter : ExpandableObjectConverter
    {
        publicoverridebool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                returntrue;
            }
            returnbase.CanConvertFrom(context, sourceType);
        }

        publicoverridebool CanConvertTo(
            ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                returntrue;
            }
            returnbase.CanConvertTo(context, destinationType);
        }

        publicoverrideobject ConvertFrom(ITypeDescriptorContext 
            context, CultureInfo culture, objectvalue)
        {
            if (value == null)
            {
                returnnew Author();
            }

            if (valueisstring)
            {
                string s = (string)value;
                if (s.Length == 0)
                {
                    returnnew Author();
                }

                string[] parts = s.Split(' ');

                        // Determine if name is stored as first and // last; first, middle, and last;// or is in error.if ((parts.Length < 2) || (parts.Length > 3))
                {
                    thrownew ArgumentException(
                        "Name must have 2 or 3 parts.", "value");
                }

                if (parts.Length == 2)
                {
                    returnnew Author(parts[0], parts[1]);
                }

                if (parts.Length == 3)
                {
                    returnnew Author(parts[0], parts[1], parts[2]);
                }
            }

            returnbase.ConvertFrom(context, culture, value);
        }

        publicoverrideobject ConvertTo(
            ITypeDescriptorContext context,
            CultureInfo culture, objectvalue, Type destinationType)
        {
            if (value != null)
            {
                if (!(valueis Author))
                {
                    thrownew ArgumentException(
                        "Invalid Author", "value");
                }
            }

            if (destinationType == typeof(string))
            {
                if (value == null)
                {
                    return String.Empty;
                }

                Author auth = (Author)value;

                if (auth.MiddleName != String.Empty)
                {
                    return String.Format("{0} {1} {2}",
                        auth.FirstName,
                        auth.MiddleName,
                        auth.LastName);
                }
                else
                {
                    return String.Format("{0} {1}",
                         auth.FirstName,
                        auth.LastName);
                }
            }

            returnbase.ConvertTo(context, culture, value, 
                destinationType);
        }
    }
}

Code Discussion

The implementation of the AuthorConverter class illustrates the tasks that you must perform to convert an instance of Author to and from a string:

  • Override the CanConvertFrom method, which determines whether an Author instance can be created from a particular type. It returns true if the type passed in is of type String.

  • Override the CanConvertTo method, which determines whether an Author instance can be converted to a particular type. It returns true if the type passed in is of type String.

  • Override the ConvertFrom method, which returns one string that contains the FirstName, MiddleName, and LastName properties of the Author instance.

  • Override the ConvertTo method, which parses a string that contains the concatenated FirstName, MiddleName, and LastName properties of an Author instance. It returns a new instance of the Author class with the data from the concatenated string.

Building and Using the Example

Compile the AuthorConverter class with the Book control and its related classes, which are described in Server Control Properties Example.

For information about compiling and using the custom control examples, see Building the Custom Server Control Examples.

See Also

Concepts

Value Types in the Common Type System

Other Resources

Developing Custom ASP.NET Server Controls