Using TypeConverter.ConvertFromString()
, I need to supply a custom format when parsing data from a string (for example, with DateTime
: "ddMMyyyy"
or "MMMM dd, yyyy"
).
TypeConverter.ConvertFromString()
has the following overload:
public object ConvertFromString(ITypeDescriptorContext context,
CultureInfo culture,
string text);
I checked up on MSDN about ITypeDescriptorContext
.
The ITypeDescriptorContext interface provides contextual information about a component. ITypeDescriptorContext is typically used at design time to provide information about a design-time container. This interface is commonly used in type conversion.
This sounds like what I need to use but I cannot find any examples anywhere.
I am using the following generic method:
public T ParseValue<T>(string value)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
Example calling code:
DateTime date = ParseValue<DateTime>("02062001");
decimal amount = ParseValue<decimal>("1.3423");
I want to be able to parse some kind of generic formatting info into this ParseValue()
method which can be used by ConvertFromString()
.
You can create a custom CultureInfo , holding your format.
Another solution would be to Wrap conversion in some helper method that would use DateTime.Parse for dates and TypeConverter for other types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With