In my sample I have used a PropertyGrid control and fetched my all properties and values.
When I change one property to an invalid value, like "123456789008765" for an integer field, it throws the following error:
I need to avoid this error, and if the given value is invalid I need to assign a default value (in this case 13, 13
). How can I do this?
Short Answer
The
PropertyGrid
uses theTypeConverter
to convert astring
to your property value and convert your property value to astring
.The error message is raised by the type converter of
Size
when converting the string to size value.You need to change the behavior for your property when converting from string. You should create a custom type converter and register it for your property to handle the exception when converting from string to your property value.
Path to solution
Here is the main problems that you should solve:
What you should know
The
PropertyGrid
uses theTypeConverter
to convert astring
to your property value and convert your property value to astring
.To customize the behavior of the property grid when converting a string to your property, you should Implement a Type Converter.
CanConvertFrom
andConvertFrom
. When you say the type can convert fromstring
then you will allow the user to type in property grid.ConvertTo
. This way you provide string representation of your property value.ExpandableObjectConverter
.TypeConverter
attribute.Size
you can useTypeDescriptor.GetConverter(typeof(Size));
Solution
The error message is raise by the type converter of
Size
. So we need to change the behavior for your property when converting from string.Based on above information we implement a custom type converter for your property. In the implementation we inherit from
ExpandableObjectConverter
, then in constructor we get the default converter forSize
and use it when overriding the mentioned methods.The main requirement is implemented in
ConvertFrom
and there we try to convert the string toSize
and when an exception occurs instead we use theDefaultValue
that you set using an attribute an if there is no default value, we use0,0
as value.Implementation
Create a converter:
And here is your class that contains a
Size
property with new converter:Don't forget to include required usings: