user2024024
user2024024

Reputation: 209

Generate random alphanumeric string

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?

Upvotes: 5

Views: 22819

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

I think this will suits your requirement,

 Private sub GenerateString()

 Dim xCharArray() As Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray
 Dim xNoArray() As Char = "0123456789".ToCharArray
 Dim xGenerator As System.Random = New System.Random()
 Dim xStr As String = String.Empty

        While xStr.Length < 6

            If xGenerator.Next(0, 2) = 0 Then
                xStr &= xCharArray(xGenerator.Next(0, xCharArray.Length))
            Else
                xStr &= xNoArray(xGenerator.Next(0, xNoArray.Length))
            End If

        End While

        MsgBox(xStr)

 End Sub

Note: Tested With IDE

EDIT: Modified according to SYSDRAGON's Comment

Upvotes: 1

SysDragon
SysDragon

Reputation: 9888

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

Upvotes: 9

Related Questions