Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random alphanumeric string

Tags:

vb.net

I am trying to generate a random code in vb.net like this

  Dim r As New Random
        Response.Write(r.Next())

But I want to generate code with 6 digits and should be alphanumeric like thie A12RV1 and all codes should be like this.

I have tried vb.net random class but I am unable to do that like as I want. I want to get the alphanumeric code each time when I execute the code. How can i achieve this in vb.net?

like image 490
user2024024 Avatar asked Mar 08 '13 07:03

user2024024


People also ask

How do you generate random alphanumeric strings?

Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.

How do I generate random alphanumeric strings in Excel?

In the Insert Random Data dialog box, click String tab, and choose the type of characters as you need, then specify the length of the string in the String length box, and finally click the OK button. See screenshot: Then the selected range has been filled with random character strings.

How do you generate random strings?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer.


1 Answers

Try something like this:

Public Function GetRandomString(ByVal iLength As Integer) As String
    Dim sResult As String = ""
    Dim rdm As New Random()

    For i As Integer = 1 To iLength
        sResult &= ChrW(rdm.Next(32, 126))
    Next

    Return sResult
End Function

Or you can do the common random string defining the valid caracters:

Public Function GenerateRandomString(ByRef iLength As Integer) As String
    Dim rdm As New Random()
    Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
    Dim sResult As String = ""

    For i As Integer = 0 To iLength - 1
        sResult += allowChrs(rdm.Next(0, allowChrs.Length))
    Next

    Return sResult
End Function
like image 154
SysDragon Avatar answered Oct 02 '22 14:10

SysDragon