By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,186 Members | 1,530 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Generating Random Numbers in VB.NET

SammyB
Expert 100+
P: 807
These are some "random" thoughts about generating random numbers in Visual Basic.

Wikipedia will give a better introduction than I, see http://en.wikipedia.org/wiki/Random_number_generator.

The key point is that you need to start the random number generator with a seed. Doing it in the form load with the number of milliseconds since midnight is an easy way to start.

The VB.Net version

This demo project will be as simple as I can make it. It consists of a form with one button. Every time you push the button, a MsgBox will pop-up with a random number between 1 and 10. This code is for VB.NET and was created with VB.NET 2005 Express Edition.

Start a new project and double click the button in the toolbox to add a button to the form. Double-click the button to see the code outline:
Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  3.     End Sub
  4. End Class
Replace that code with:
Expand|Select|Wrap|Line Numbers
  1. Public Class Form1
  2.     Private oRand As Random
  3.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  4.         oRand = New Random(DateTime.Now.Millisecond)
  5.     End Sub
  6.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  7.         Dim iRand As Integer
  8.         iRand = oRand.Next(1, 10)
  9.         MsgBox(iRand)
  10.     End Sub
  11. End Class
Notice the following key items:
  1. oRand is the Random number Generator and is defined at the module level
  2. oRand is initialized once in the Form Load event using the millisecong component of the current time.
  3. The Next method of the Random object generates a new number.
May 4 '07 #1
Share this Article
Share on Google+