Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Friday, 6 February 2015

Introduction:  

 In this article I will explain how to generate unique alpha-numeric random number in asp.net using both C# and VB.Net language.

 Description: 
While development, sometime we need to use random alphanumeric random value. E.g. to concatenate random number with the name of the file to upload through FileUploadcontrol to make that file unique in the uploaded folder or to generate random password.


Implementation: Place a Button Control on design page(.aspx)
<asp:Button ID="btnRandomNumber" runat="server" Text="Generate"
            onclick="btnRandomNumber_Click" />

C#.Net Code to create/generate unique random alphanumeric value in asp.net

  • In the code behind file(.aspx.cs) write the code as:
    protected void btnRandomNumber_Click(object sender, EventArgs e)
    {
        string num = GenerateRandomNumber(5);
    } 

    public static string GenerateRandomNumber(int Length)
    {
        string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
        Random randNum = new Random();
        char[] chars = new char[Length];
        int allowedCharCount = _allowedChars.Length;

        for (int i = 0; i <= Length - 1; i++)
        {
            chars[i] = _allowedChars[Convert.ToInt32((_allowedChars.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }

VB.Net Code to create/generate unique random alpha-numeric value in asp.net

  •  In the code behind file(.aspx.vb) write the code as:
Protected Sub btnRandomNumber_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim num As String = GenerateRandomNumber(5)
    End Sub

    Public Shared Function GenerateRandomNumber(ByVal Length As Integer) As String
        Dim _allowedChars As String ="abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
        Dim randNum As New Random()
        Dim chars As Char() = New Char(Length - 1) {}
        Dim allowedCharCount As Integer = _allowedChars.Length

        For i As Integer = 0 To Length - 1
            chars(i) = _allowedChars(Convert.ToInt32((_allowedChars.Length) * randNum.NextDouble()))
        Next


        Return New String(chars)

    End Function
Categories: , ,

0 comments:

Post a Comment