How can I pad an integer to make sure it is always three digits in vb.net at the DTO level?

472 Views Asked by At

I have a field in my DTO that is an integer. In the database, there are some numbers stored as 1, 2, 101 etc. I want to make sure in the system they are always display as three digits, so 001, 002 for example. This is not working and I cannot figure out how to do it...any ideas out there? Here is the snippet from my DTO:

Private mArea As Integer
<Display(name:="Area")> _
<DisplayFormat(DataformatString:="{0:000}")> _
Public Property Area() As Integer
    Get
        Return mArea
    End Get
    Set(ByVal value As Integer)
        mArea = value
    End Set
End Property
3

There are 3 best solutions below

0
On

You could treat the value as a string.

Dim areaString As String = Strings.Right("000" & area.ToString, 3)
0
On

First off, VB will automatically create a backing field for you, so you should be able to simplify your existing property declaration as:

<Display(name:="Area"), DisplayFormat(DataformatString:="{0:000}")>
Public Property Area As Integer

As mentioned, the attributes on the property may or may not be applicable to the container and so may not be honored. Something I've done in other projects is create a templated Value class, such as:

Public MustInherit Class Value(Of T)
    Public Overridable Property Value As T
    Public MustOverride ReadOnly Property DisplayValue As String
End Class

Public Class AreaValue
    Inherits Value(Of Integer)

    Public Overrides ReadOnly Property DisplayValue As String
        Get
            Return Format(Value, "000")
        End Get
    End Property
End Class

Then you have full control to distinguish between what's displayed and what is stored.

Otherwise, you could just preface each location you display Area as:

Format(Area,"000")

Or something similar. Probably best though to abstract out your intent of separating display values from stored values.

0
On

The DisplayFormat attribute is just an information. Some UI Controls (for example some WPF controls) use it and respect it. It is just a hint. It changes not, how the integer is stored. An integer is stored as binary value. It has no inherent format or leading or trailing zeros (decimal has to some degree).

To reach your goal you have to format every output of the field you make in your application, or use UI Controls that respect the DisplayFormat attribute.