Add leading zeros

Posted on 2007-08-02
Last Modified: 2010-04-23
Hi all,

I am using VB.NET (VS 2003).

I have a numeric value that I am retrieving from a SQL Server database. This could be anything from 1 to 999.

What I want to do is to always have the value showing as 3 digits in the textbox on my VB form. ie.
3 = 003
11 = 011
97 = 097
100 = 100

Any ideas guys?

Question by:FMabey
    LVL 142

    Expert Comment

    by:Guy Hengel [angelIII / a3]
    one possibility:
    yourstring = yourvariable.ToString().LeftPad(3, '0');
    LVL 3

    Author Comment


    Cheers for the speedy response.

    I have entered the following code:

            Dim STR_id As String
            STR_id = TXT_id.Text
            TXT_test.text = STR_id.ToString().LeftPad(3, '0')

    It tells me that 'leftpad is not a member of string'. Any ideas where I'm going wrong?
    LVL 48

    Expert Comment

    You can use

    Dim value As Integer = 3
    MsgBox(Format(value, "000"))
    LVL 142

    Accepted Solution

    sorry, my error, the function is called PadLeft():

            Dim STR_id As String
            STR_id = TXT_id.Text
            TXT_test.text = STR_id.ToString().PadLeft(3, '0')
    LVL 3

    Author Comment


    Thanks angellll. Just to make one ammendmant for anyone searching on this. The code I used was this...

            Dim STR_id As String
            STR_id = TXT_id.Text
            TXT_test.text = STR_id.ToString().PadLeft(3, "0")

    The only alteration was '0' changed to "0".

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Introduction When many people think of the WebBrowser ( control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
    Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now