Using custom TypeConverter outside of PropertyGrid

C

Cartoper

I have written all these wonderful custom TypeConverter for my enums
to display in a PropertyGrid. I would now like to use the same
TypeConverter to save out and read in the values to and from a text
file, in a generic fashion. I would like to have a function like
this:

void WriteValue(StreamWriter sw, string name, Enum value);
 
C

Cartoper

As I walked to lunch it dawned on me that I might be able to get at
the attributes via the GetType() method. Well, I wasn't able to, but
I did realize that as long as you follow the convention of <enum
name>TypeConverter, that through reflections you can instanciate the
enum's TypeConverter:

// start by using the default ToString method
string valueStr = Value.ToString();

try
{
// Get the enum type
Type enumType = Value.GetType();

// Get the enum name and then add the TypeConverter to the end of it
string typeConverterName = enumType.FullName + "TypeConverter";

// Get the assembly that the enum is in.
string assemblyName = enumType.Assembly.FullName;

// try to create the type converter
ObjectHandle objHandle =
Thread.GetDomain().CreateInstance(assemblyName, typeConverterName);

// Get the TypeConverter from the object handle
TypeConverter typeConverter = objHandle.Unwrap() as TypeConverter;

// Convert it to a string
valueStr = typeConverter.ConvertToString(Value);
}
catch(Exception)
{
}
 
M

Marc Gravell

or in fact TypeDescriptor.GetConverter(Value);

I'm also assuming that the enum is marked with TypeConverterAttribute

Marc
 
C

Cartoper

or in fact TypeDescriptor.GetConverter(Value);

I'm also assuming that the enum is marked with TypeConverterAttribute

Marc

Marc,

Where where you Friday, you could have saved me a lot of work;)
Thanks for the tip!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top