-
Mar 3rd, 2019, 08:55 AM
#1
Thread Starter
Lively Member
[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...
Here is a picture of my current output and what my code does...
Any suggestions, ideas, tips would be very appreciated and thank you for your time!!!
-
Mar 3rd, 2019, 09:05 AM
#2
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.
-
Mar 3rd, 2019, 11:21 AM
#3
Thread Starter
Lively Member
Re: Create Random Strings - Issue
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!!!
-
Mar 4th, 2019, 09:21 AM
#4
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
-
Mar 4th, 2019, 03:32 PM
#5
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
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|