Click here to Skip to main content
15,922,007 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have never used random before in VB and i was wondering... I have 4 textboxes which have text inserted into them. Now when i click a button i wish to randomize the text(not the actual text) so that each of the 4 words go into a random textbox between the 4 textboxes. How would this be done. Bear in mind i am new to VB and would like to learn.

What I have tried:

I have no idea where to start i know i may need to declare a random object but thats about it. Please help.
Updated 27-Jan-19 4:13am

1 solution

Let me see if I understand you first - your explanation isn't that clear.
You have four text boxes:
  1       2      3      4
Hello   There   My   Friend
And you want to press a button and "swap" the text about randomly:
  1       2      3      4
There  Friend   My    Hello
  1       2      3      4
My     Friend  There  Hello
And so on.

That's not difficult to do, but to make it easier, create an array of strings and copy the text into it:
Dim data As String() = New String(3) {}
data(0) = textBox1.Text
data(1) = textBox2.Text
data(2) = textBox3.Text
data(3) = textBox4.Text
Now, you can just use the index number to decide what to move around.
So create a Random instance, and run a loop:
Dim rand As Random = New Random()

For i As Integer = 0 To 10 - 1
The loop runs more times than there are elements to really mix them about!
Inside the loop, generate two indexes from the Random generator, and swap the elements:
Dim index1 As Integer = rand.[Next](4)
Dim index2 As Integer = rand.[Next](4)
Dim temp As String = data(index1)
data(index1) = data(index2)
data(index2) = temp

Now all you have to do is put the strings back into the text boxes!
textBox1.Text = data(0)
textBox2.Text = data(1)
textBox3.Text = data(2)
textBox4.Text = data(3)
All done!
Share this answer
CPallini 27-Jan-19 12:09pm    
My 5.
Maciej Los 6-Feb-19 6:24am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900