Padding Left Side Of Number - VB.NET

Hi,

I have a database field to represent in fixed length - Say length (7). If i have a value "123" from database then i want to represent it with "0000123". Similarly for "1234", i want to represent it with "0001234". Can you please provide me simple function which will do this task in VB.NET ?

Thanks
milani_lucieAsked:
Who is Participating?
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
If you are working with STRING values from the DB then use String.PadLeft() or String.PadRight().
0
 
Kevin CrossChief Technology OfficerCommented:
One method is using ToString with format string like "0000000" or "#0000000".  Alternatively, you could do this on the database end by converting the INT to varchar and then concatenting '0000000' in front of it and then taking the right 7 characters.
Dim i As Integer = 123
MsgBox(i.ToString("0000000"))

Open in new window

0
 
Kevin CrossChief Technology OfficerCommented:
The VB.NET way more quickly adapts to numbers greater than 7 characters if you ever breach the limits of the 7 digits.  However, here is the SQL version (MS SQL example).
SELECT RIGHT('0000000' + CAST(123 AS VARCHAR(10)), 7);

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
Kevin CrossChief Technology OfficerCommented:
Are those still around?  Nice suggestion, Idle Mind.  I use to love using those functions think was in MS Access then Microsoft decided to get rid of them for whatever reason.  Forgot they are now back, or maybe I was misinformed all these years. ;)
0
 
barrislbCommented:
Hi milani_lucie,

I'm just providing some sample code to what Idle Mind suggested. I'm a little late in, but nevertheless, I still can assist.  :- )

mwvisa1: yes,  the pad methods are still around. :- ) The PadLeft and PadRight, actually replaced the LSet() and RSet() functions of VB 6.
Dim PadString As String = "1234".PadLeft(7, "0")
MessageBox.Show(RightPadString)

Open in new window

0
 
barrislbCommented:
MessageBox.Show(RightPadString)  Should Be: MessageBox.Show(PadString)




0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.