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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With