Generate random alphanumeric string

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

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

But I want to generate a 6-digit code and should be alphanumeric like thie A12RV1 , and all codes should be like that.

I tried the random vb.net class, but I can't do it the way I want. I want to get an alphanumeric code every time I execute the code. How can I achieve this in vb.net?

+4
source share
2 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 make a regular random string defining valid characters:

 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 
+3
source

I think it will meet 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 Comment

+1
source

All Articles