Add leading zero (0) to auto increment number in ASP.Net using C# and VB.Net

micah
 
on Mar 22, 2021 11:21 PM
Sample_895942.zip
2726 Views

This example shows how to increment a value using viewstate, but i want it to increment value from start like 001, 002, 003 instead of incrementing like 1,2,3,4 etc.

protected void IncreamentCounter(object sender, EventArgs e)
{
    int counter;
    if (ViewState["Count"] != null)
    {
        counter = Convert.ToInt32(ViewState["Count"]);
    }
    else
    {
        counter = 0;
    }
    counter = counter + 1;
    ViewState["Count"] = counter;
    this.lblCount.Text = counter.ToString();
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 23, 2021 02:37 AM

Hi micah,

Check this example. Now please take its reference and correct your code.

HTML

<asp:Label ID="lblCount" runat="server" />
<asp:Button Text="Increament counter" OnClick="IncreamentCounter" runat="server" />

Code

C#

protected void IncreamentCounter(object sender, EventArgs e)
{
    int counter;
    if (ViewState["Count"] != null)
    {
        counter = Convert.ToInt32(ViewState["Count"]);
    }
    else
    {
        counter = 0;
    }
    counter = counter + 1;
    ViewState["Count"] = counter;
    this.lblCount.Text = counter.ToString().PadLeft(3, '0');
}

VB.Net

Protected Sub IncreamentCounter(ByVal sender As Object, ByVal e As EventArgs)
    Dim counter As Integer
    If ViewState("Count") IsNot Nothing Then
        counter = Convert.ToInt32(ViewState("Count"))
    Else
        counter = 0
    End If
    counter = counter + 1
    ViewState("Count") = counter
    Me.lblCount.Text = counter.ToString().PadLeft(3, "0"c)
End Sub

Screenshot