Results 1 to 8 of 8

Thread: [RESOLVED] Nullable Property question

  1. #1

    Thread Starter
    PowerPoster Nitesh's Avatar
    Join Date
    Mar 2007
    Location
    Death Valley
    Posts
    2,556

    Resolved [RESOLVED] Nullable Property question

    Hi All,

    I have Nullable properties in my class:

    Code:
    Public Property FileStatusID() As Integer?
            Get
                Return m_FileStatusID
            End Get
            Set(ByVal value As Integer?)
                m_FileStatusID = value
            End Set
        End Property
    I assumed I would be able to store null values in the property. But when I try to assign a value from a datatable row like this:

    Code:
    File.FileStatusID = filetable.Rows(0)("FileStatusID")
    I get an Invalid Cast error when a null value is encountered. Do I have to do an ISDBNull check?? what's the best way?

  2. #2
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Nullable Property question

    A database null value is 'DBNull.Value', which is not equal to a VB null value, which is 'Nothing'.
    You'd have to check if your database returns DBNull.Value, and in that case assign Nothing. I usually use something like this:
    Code:
    Private Function ToInt(ByVal obj As Object) As Integer?
       If obj Is Nothing OrElse obj Is DBNull.Value Then Return Nothing
       Return CInt(obj)
    End Function

  3. #3

    Thread Starter
    PowerPoster Nitesh's Avatar
    Join Date
    Mar 2007
    Location
    Death Valley
    Posts
    2,556

    Re: Nullable Property question

    thanks NickThissen will try it out now

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

    Re: Nullable Property question

    You can store Nothing is a nullable value type but database nulls are not Nothing. They are instances of the DBNull class, so they are definitely something. NT's code will work but, assuming .NET 3.5 or later, it's much simpler than that. In fact, you already know how to do it because I showed you in your last thread. I guess it didn't sink in.
    Code:
    File.FileStatusID = filetable.Rows(0).Field(Of Integer?)("FileStatusID")
    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
    PowerPoster Nitesh's Avatar
    Join Date
    Mar 2007
    Location
    Death Valley
    Posts
    2,556

    Re: Nullable Property question

    thanks JM. it has sunk in now

    One more question. say my property has a value of nothing.

    If I try to assign the property value to a textbox I get an error saying:

    Code:
    Nullable object must have a value.
    what's the correct way to handle this. I've seen some solutions but I'm not so happy with them

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

    Re: Nullable Property question

    If you want a String then you just call ToString. If there's a value then you'll get that value converted to a String and if there isn't a value then you'll get an empty String. If you actually want to use the value if there is one then you can use the HasValue and Value properties, e.g.
    vb.net Code:
    1. Dim myInteger As Integer
    2.  
    3. If myNullableInteger.HasValue Then
    4.     myInteger = myNullableInteger.Value
    5. Else
    6.     myInteger = 0
    7. End If
    There are situations where you would need to use HasValue and Value but, if you want to do what I have above, then it can be done more simply like so:
    vb.net Code:
    1. Dim myInteger As Integer = myNullableInteger.GetValueOrDefault()
    With no argument, GetValueOrDefault will return the default value for the type if HasValue is False. If you want to specify a different default value, pass that to the method as an argument.
    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
    PowerPoster Nitesh's Avatar
    Join Date
    Mar 2007
    Location
    Death Valley
    Posts
    2,556

    Re: Nullable Property question

    thanks again JM. works great

  8. #8

    Thread Starter
    PowerPoster Nitesh's Avatar
    Join Date
    Mar 2007
    Location
    Death Valley
    Posts
    2,556

    Re: [RESOLVED] Nullable Property question

    hey guys,

    JUst posting this here to help someone else incase they ever come across it. I always used to assign date.MinValue to my Date Variables if the db value was null.

    Now with nullable types it just added a new dimension in handling null values. thanks to JM i've gained even more knowledge and I am so happy that I'm using the best possible methods.

    So the thing with nullable datetime properties is that you can't format them using the ToString method Like I used to:

    Code:
    Datevar.ToString("yyyy/MM/dd")
    so after some research I stumbled upon Extension methods. What you have to do is:

    Since I'm using asp.net: Add a class to your project. Replace the word class with Module.

    add the Extension Attribute to your functions and subs:

    Code:
    Imports Microsoft.VisualBasic
    Imports System.Runtime.CompilerServices
    Public Module Extensions
        <Extension()> _
    Public Function ToString(ByVal dateTime As System.Nullable(Of DateTime), ByVal format As String) As String
    
            Return dateTime.ToString(format, "")
    
        End Function
    
        <Extension()> _
        Public Function ToString(ByVal dateTime As System.Nullable(Of DateTime), ByVal format As String, ByVal returnIfNull As String) As String
            If dateTime.HasValue Then
                Return dateTime.Value.ToString(format)
            Else
                Return returnIfNull
            End If
    
        End Function
    
        <Extension()> _
        Public Function ToShortDateString(ByVal dateTime As System.Nullable(Of DateTime)) As String
    
            Return dateTime.ToShortDateString("")
    
        End Function
        <Extension()> _
        Public Function ToShortDateString(ByVal dateTime As System.Nullable(Of DateTime), ByVal returnIfNull As String) As String
    
            If dateTime.HasValue Then
                Return dateTime.Value.ToShortDateString()
            Else
    
                Return returnIfNull
            End If
    
        End Function
    
    End Module
    Then Just Add an Import.Extensions to your page. With this Extension method defined above, you will now be able to call
    Code:
    .ToShortDateString(string.empty)
    directly on your Nullable DateTime types and it will either return the actual DateTime formatted according to the format string, or it will return a blank string.

    example usage: I have a nullable DateTime Property ReOpenedDate in my File Class. To assign it's value to a textbox I do this:

    Code:
    Me.txtReopenedDate.Text = File.ReOpenedDate.ToShortDateString(String.Empty)
    so much more elegant than checking for Date.Minvalue

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