Export (0) Print
Expand All

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.

// AuthorConverter.cs
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;

namespace Samples.AspNet.CS.Controls
{
    public class AuthorConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

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

        public override object ConvertFrom(ITypeDescriptorContext 
            context, CultureInfo culture, object value)
        {
            if (value == null)
            {
                return new Author();
            }

            if (value is string)
            {
                string s = (string)value;
                if (s.Length == 0)
                {
                    return new 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))
                {
                    throw new ArgumentException(
                        "Name must have 2 or 3 parts.", "value");
                }

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

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

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

        public override object ConvertTo(
            ITypeDescriptorContext context,
            CultureInfo culture, object value, Type destinationType)
        {
            if (value != null)
            {
                if (!(value is Author))
                {
                    throw new 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);
                }
            }

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


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.

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.

Community Additions

ADD
Show:
© 2015 Microsoft