Results 1 to 10 of 10

Thread: Dealing with wrong data types in class properties

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2007
    Posts
    36

    Dealing with wrong data types in class properties

    How do I manage the wrong data type being sent to a class property? I'm using a property Grid, and I have bound the values to an object (my own, so I can modify the code).

    So, for example, I have an object property of type Integer. This is bound to a property Grid value. The user type "Tosh", and an error is displayed telling me the value is incompatible.

    I can't see a way to catch the exception, as it occurs as the value is passed to the object property.

    This is the extended version of the control from CodeProject.
    Property code:

    Code:
    Property sizeX() As Single
    
            Get
                Return sSize.X
            End Get
    
            Set(ByVal value As Single)
                If value > sMax.X Then
                    Throw New System.Exception("Value (" & value.ToString & " is too large. Maximum is " & sMax.X.ToString)
                Else
                    If value <= 0 Then
                        Throw New System.Exception("Value must be > 0")
                    Else
                        sSize.X = value
                    End If
                End If
            End Set
    
        End Property
    Implementation of the value:

    Code:
    .Item.Add(cLBL_WORLD_X, world, "sizeX", False, cWORLDPROPERTIES, cLBL_WORLD_X_DESC, True)

  2. #2
    Hyperactive Member
    Join Date
    Feb 2006
    Location
    UK
    Posts
    285

    Re: Dealing with wrong data types in class properties

    Implement your property as Object and use a class derived from TypeConverter ...
    vb.net Code:
    1. Private m_SizeX As Single
    2.  
    3.     <TypeConverter(GetType(SizeXConverter))> _
    4.     Public Property SizeX() As Object
    5.         Get
    6.             Return m_SizeX
    7.         End Get
    8.         Set(ByVal value As Object)
    9.             m_SizeX = CType(value, Single)
    10.         End Set
    11.     End Property
    12.  
    13.  
    14.  
    15. Public Class SizeXConverter
    16.     Inherits TypeConverter
    17.  
    18.     Public Overrides Function CanConvertFrom(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal sourceType As System.Type) As Boolean
    19.         If sourceType.Equals(GetType(String)) Then
    20.             Return True
    21.         Else
    22.             Return MyBase.CanConvertFrom(context, sourceType)
    23.         End If
    24.     End Function
    25.  
    26.     Public Overrides Function ConvertFrom(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object) As Object
    27.         Try
    28.             Dim c As Single = CSng(value), s As String = String.Empty
    29.             Select Case True
    30.                 Case c > Single.MaxValue
    31.                     s = "Number entered is too high!"
    32.                 Case c < Single.MinValue
    33.                     s = "Number entered is too low!"
    34.             End Select
    35.             If s <> String.Empty Then Throw New InvalidCastException(s)
    36.             Return c
    37.         Catch ex As InvalidCastException
    38.             MsgBox(ex.ToString)
    39.             Return CSng(0)
    40.         End Try
    41.     End Function
    42. End Class

    This code works relatively well, except that the error message shows at least twice, but I can't figure out why. If anyone can, please post...

  3. #3
    Hyperactive Member
    Join Date
    Feb 2006
    Location
    UK
    Posts
    285

    Re: Dealing with wrong data types in class properties

    #2 works for invalid entries in the propertygrid. For invalid entries in your code, you will of course catch the error at source...

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Dealing with wrong data types in class properties

    Declaring your property as type Object when it is supposed to represent a Single is simply not a practical option. You'd get no type safety at design time then.

    The reason that you can't catch an exception is because there is no exception. The value never gets as far as your property. Run your app and enter and invalid value and watch the Output window. There's no mention of a first chance exception because no exception is ever thrown. The PropertyGrid validates the data before it ever even tries to set your property.

    If you wanted to intercept this situation then it would have to be via an event of the PropertyGrid itself, but as far as I can see there's no event raised when invalid data is entered.

    Given that the PropertyGrid notifies the user of the error and allows them to retry or cancel, why exactly do you want do this anyway? Are you looking to provide a more idiot-friendly error message? If you want to describe a valid value to the user you can apply the Description attribute to your property, whose value will then be displayed at the bottom of the grid when that property is selected.
    Attached Images Attached Images  
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Member
    Join Date
    Jun 2007
    Posts
    36

    Re: Dealing with wrong data types in class properties

    Thanks for the info so far. I have a description, so that side is covered. My issue is that the error looks quite daunting to a non-technical person. It makes perfect sense to me as the developer, but it doesn't provide a solution to an end-user, only a cause. Additionally, I would like to be able to revert the value back to the original if it's invalid.

    I have a solution where I don't bind the values, and handle it all manually. It's fine, but very long-winded when the option is there to "take care of itself".


  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Dealing with wrong data types in class properties

    If the user presses the Cancel button on that dialogue the value displayed in the grid will revert to the current property value, while pressing OK will leave the pending value displayed and selected.

    It probably would have been smart for them to have provided an event that was raised before that dialogue was shown, allowing you to provide a custom message and perhaps some other things. I've scoured the documentation for the PropertyGrid and also had a good look at it in Reflector and I can't see anything that would allow you to change that message or display your own dialogue.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Member
    Join Date
    Jun 2007
    Posts
    36

    Re: Dealing with wrong data types in class properties

    OK, thanks again for all your help. I'll stick with my manual handling option.

  8. #8
    Hyperactive Member
    Join Date
    Feb 2006
    Location
    UK
    Posts
    285

    Re: Dealing with wrong data types in class properties

    Did you actually try the effting thing I posted? It does what you said you wanted!

  9. #9

    Thread Starter
    Member
    Join Date
    Jun 2007
    Posts
    36

    Re: Dealing with wrong data types in class properties

    BigMeUp, I haven't, but for 2 reasons. Firstly it is quite complex to understand at my level of VB, and I like to code in a way that I can maintain the code afterwards. I'm sure that at some point in the future it will make far more sense for me to look at inmore detail.
    Secondly, I didn't because...

    Declaring your property as type Object when it is supposed to represent a Single is simply not a practical option. You'd get no type safety at design time then.
    I still appreciate your input though!

  10. #10
    Hyperactive Member
    Join Date
    Feb 2006
    Location
    UK
    Posts
    285

    Re: Dealing with wrong data types in class properties

    I fully understand and appreciate your first point. The second point though is rigidity gone mad! There are good reasons to adhere to type-safety rules, but a good programmer should understand the risks and know when to stick to the rules, and when he can safely break them.

    Looking closely over what I posted, you will find I catch all (design time) InvalidCastExceptions - therefore, the issue of type safety at design time simply doesn't arise. WE ARE EXPECTING CASTING ERRORS, THAT IS WHY WE ARE WRITING THIS CODE!!!!

    Please free your mind from unnecessry constraints. Thinking outside the box will ultimately reward you with elegant solutions.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width