Generate limited random number and add hyphen (-) after each 4th character in asp.net

In this article I am going to explain how to generate limited random number and add hyphen after each 4th character in asp.net.


Description:
I want to generate 16 unique number and after each 4th number insert hyphen (-).
Implementation:

HTML Markup:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:Button ID="btnsubmit" runat="server" Text="Button" />
    <asp:Label ID="lblnumber" runat="server"></asp:Label>   
    </div>
    </form>
</body>
</html>


C# Code:

string randomno;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        try
        {          
            for (int i = 0; i < 1; i++)
            {
                Guid g = Guid.NewGuid();
                string random = g.ToString();
                string s = random.Replace("-", "");
                randomno = s.Substring(0, 16);
                int loc = 4;
                for (int ins = loc; ins < randomno.Length; ins += loc + 1)
                    randomno = randomno.Insert(ins, "-");
            }
            lblnumber.Text = randomno.ToString();
        }
        catch (Exception ex) { }
    }



VB.net Code:

Dim randomno As String
    Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
        Try
            For i As Integer = 0 To 0
                Dim g As Guid = Guid.NewGuid()
                Dim random As String = g.ToString()
                Dim s As String = random.Replace("-", "")
                randomno = s.Substring(0, 16)
                Dim loc As Integer = 4
                Dim ins As Integer = loc
                While ins < randomno.Length
                    randomno = randomno.Insert(ins, "-")
                    ins += loc + 1
                End While
            Next
            lblnumber.Text = randomno.ToString()
        Catch ex As Exception
        End Try
    End Sub





Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget