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

Home
ASP.NET Tutorial
1.ASP.Net Instroduction
2.Language Basics
3.ASP.net Controls
4.HTML Controls
5.Page Lifecycle
6.Response
7.Collections
8.Validation
9.Development
10.File Directory
11.Sessions
12.Cookie
13.Cache
14.Custom Controls
15.Profile
16.Configuration
17.LINQ
18.ADO.net Database
19.Data Binding
20.Ajax
21.Authentication Authorization
22.I18N
23.Mobile
24.WebPart
25.XML
ASP.NET Tutorial » Custom Controls » TypeConverter 
14.17.3.Creating a custom type converter (C#)
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)
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.