How to generate and 7-digit random number/special character string in VB.Net?
How can I generate a 7-digit random numbe开发者_如何学Cr and special character string in a textbox on a button click event, in VB.Net?
Put the characters you want in a string and pick from that:
Dim chars As String = "0123456789abcdefghijklmnopqrstuvwxyz!#%&()?+-;:"
Dim word As Char() = New Char(6)
Dim rnd As New Random()
For i As Integer = 0 To word.Length - 1
word(i) = chars.Chars(rnd.Next(chars.Length))
Next
TheTextBox.Text = New String(word)
here is a light weight version i use:
Protected Function GetRandomPass() As String
Dim pass As String = String.Empty
Dim AllowedChars() As String = {"ABCDEFGHJKLMNPQRSTWXYZ", "abcdefghjklmnpqrstwxyz", "0123456789"}
Dim rnd = New Random()
While pass.Length < 10
Dim rndSet As Integer = rnd.Next(0, AllowedChars.Length)
pass &= AllowedChars(rndSet).Substring(rnd.Next(0, AllowedChars(rndSet).Length), 1)
End While
Return pass
End Function
it chooses a random index of the AllowedChars()
array and then chooses a random character in that index using the substring
property and appends it to the pass
string when the string reaches the defined length it returns the randomly generated password.
this way you can keep your character types separate and also have the ability to add more items to the AllowedChars()
array with out editing the rest of the function
I know you could do this with just a plain string and get a random substring
out of it but i prefer to see the differences between UPPER, lowercase, and num3r1c/($pec|@|_) characters.
精彩评论