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.vb
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design.Serialization
Imports System.Globalization
Imports System.Reflection
Namespace Samples.AspNet.VB.Controls
Public Class AuthorConverter
Inherits ExpandableObjectConverter
Public Overrides Function CanConvertFrom( _
ByVal context As ITypeDescriptorContext, _
ByVal sourceType As Type) As Boolean
If sourceType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertFrom(context, sourceType)
End Function
Public Overrides Function CanConvertTo( _
ByVal context As ITypeDescriptorContext, _
ByVal destinationType As Type) As Boolean
If destinationType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertTo(context, destinationType)
End Function
Public Overrides Function ConvertFrom( _
ByVal context As ITypeDescriptorContext, _
ByVal culture As CultureInfo, ByVal value As Object) As Object
If value Is Nothing Then
Return New Author()
End If
If (TypeOf value Is String) Then
Dim s As String = CStr(value)
If s.Length = 0 Then
Return New Author()
End If
Dim parts() As String = 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) Then
Throw New ArgumentException( _
"Name must have 2 or 3 parts.", "value")
End If
If parts.Length = 2 Then
Return New Author(parts(0), parts(1))
End If
If parts.Length = 3 Then
Return New Author(parts(0), parts(1), parts(2))
End If
End If
Return MyBase.ConvertFrom(context, culture, value)
End Function
Public Overrides Function ConvertTo( _
ByVal context As ITypeDescriptorContext, _
ByVal culture As CultureInfo, ByVal value As Object, _
ByVal destinationType As Type) As Object
If value IsNot Nothing Then
If Not (TypeOf value Is Author) Then
Throw New ArgumentException("Invalid Author", _
"value")
End If
End If
If destinationType Is GetType(String) Then
If value Is Nothing Then
Return String.Empty
End If
Dim auth As Author = CType(value, Author)
If auth.MiddleName <> String.Empty Then
Return String.Format("{0} {1} {2}", _
auth.FirstName, _
auth.MiddleName, _
auth.LastName)
Else
Return String.Format("{0} {1}", _
auth.FirstName, _
auth.LastName)
End If
End If
Return MyBase.ConvertTo(context, culture, value, _
destinationType)
End Function
End Class
End Namespace
// 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);
}
}
}
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.