Generate Random Number Within a predetermined range - VB.NET

I am trying to generate a random number in a VB .Net application but I need the number to be within a predetermined range (the range will be 0 to TotalCount).

I know this can be done, but it's been forever since I've done it and I nolonger have MSDN information files available.

If anyone has any ideas, let me know.


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hi Rorc,

Please see this page:

Basically something like:

Dim RandomClass As New Random()
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(TotalCount)

Should do it


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RorcAuthor Commented:
Thank you, I knew it could be done but just couldn't remember how.
Mike TomlinsonMiddle School Assistant TeacherCommented:
Just remember that the value passed into the Next method is NOT included.  In the example below, a number between 0 and 14 inclusive will be returned:

        Dim TotalCount As Integer = 15
        Dim RandomClass As New Random
        Dim RandomNumber As Integer
        RandomNumber = RandomClass.Next(TotalCount)

Here is the Random.Next() help:

From the Return value remarks:
"A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not MaxValue. If minValue equals maxValue, minValue is returned."

This also holds true for the Next() method that acceps two parameters.  The first value will be included but the second will not:

        Dim RandomClass As New Random
        Dim RandomNumber As Integer
        RandomNumber = RandomClass.Next(4, 15)

The above will return a value between 4 and 14 inclusive.


It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.