2 Attachment(s)
[RESOLVED] Create Random Strings - Issue
Hi,
I am currently working on a project when button1 is pressed, it will generate different and random keys into textboxes.
So for example, button1 is pressed and this happens to four textboxes...
TextBox1: 1kjnkj3n
TextBox2: 4kj32n4
TextBox3: 5kjnssd
TextBox4: dskjnwS
...This is my goal.
BUT
I am using this code below as a function to generate the keys, however, it does not generate a new code for every textbox, instead every textbox is assigned the same random key.
Code:
Private Function CipherKeyGenerated()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi123"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 7
Dim idx As Integer = r.Next(0, 18)
sb.Append(s.Substring(idx, 1))
Next
Return (sb.ToString())
End Function
To call the function for each of the textboxes under the button1_click event, I am using:
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = CipherKeyGenerated()
TextBox2.Text = CipherKeyGenerated()
TextBox3.Text = CipherKeyGenerated()
TextBox4.Text = CipherKeyGenerated()
End Sub
Here is a picture of what I need the output to look like...
Attachment 166105
Here is a picture of my current output and what my code does...
Attachment 166107
Any suggestions, ideas, tips would be very appreciated and thank you for your time!!! :)
Re: Create Random Strings - Issue
Try movinf the dim r as New Random to outside of the function. Every time you are creating a new instance it is re-seeding the random number generator, if you create them quickly enough they will all have the same seed.
Re: Create Random Strings - Issue
Quote:
Originally Posted by
PlausiblyDamp
Try movinf the dim r as New Random to outside of the function. Every time you are creating a new instance it is re-seeding the random number generator, if you create them quickly enough they will all have the same seed.
Awesome!!! This worked perfectly!!!
Re: [RESOLVED] Create Random Strings - Issue
Rewrite of the function
Code:
Private PRNG As New Random
Private Function CipherKeyGenerated() As String
Static s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi123"
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To 7
Dim idx As Integer = PRNG.Next(0, s.Length)
sb.Append(s(idx))
Next
Return (sb.ToString())
End Function
Re: [RESOLVED] Create Random Strings - Issue
Sitten wrote a good example of Random using a number of techniques.
http://www.vbforums.com/showthread.p...=1#post3914156