GuidConverter.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // System.ComponentModel.GuidConverter
  3. //
  4. // Author:
  5. // Andreas Nahr ([email protected])
  6. //
  7. // (C) 2003 Andreas Nahr
  8. //
  9. using System.Globalization;
  10. namespace System.ComponentModel
  11. {
  12. public class GuidConverter : TypeConverter
  13. {
  14. public GuidConverter()
  15. {
  16. }
  17. public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
  18. {
  19. if (sourceType == typeof (string))
  20. return true;
  21. return base.CanConvertFrom (context, sourceType);
  22. }
  23. public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
  24. {
  25. if (destinationType == typeof (string))
  26. return true;
  27. return base.CanConvertTo (context, destinationType);
  28. }
  29. public override object ConvertFrom (ITypeDescriptorContext context,
  30. CultureInfo culture, object value)
  31. {
  32. if (value.GetType() == typeof (string)) {
  33. string GuidString = (string) value;
  34. try {
  35. return new Guid (GuidString);
  36. } catch {
  37. throw new FormatException (GuidString + "is not a valid GUID.");
  38. }
  39. }
  40. return base.ConvertFrom (context, culture, value);
  41. }
  42. public override object ConvertTo (ITypeDescriptorContext context,
  43. CultureInfo culture, object value, Type destinationType)
  44. {
  45. if (destinationType == typeof (string) && value != null &&value.GetType() == typeof (Guid))
  46. // LAMESPEC MS seems to always parse "D" type
  47. return ((Guid) value).ToString("D");
  48. return base.ConvertTo (context, culture, value, destinationType);
  49. }
  50. }
  51. }