How to Generate Random Numbers Within a Specific Range

Introduction

Sometimes developers need to generate random numbers and for this you use Random class in C# that resides in the "System" namespace.

random image

But what will you do when the client needs some specific random numbers within a range, like 100 to 200 or may be 1000 to 2000.

The following are the details for the preceding requirements.

Step 1

Create a new empty Website named "Website1'.

new web site

And add the Web form named "Deafult.aspx' into it.

new website(2)

Step 2

Add 2 Textboxes for "minimum value" and "maximum value" and a button in the "Deafult.aspx' page with the text "Generate Random Number in a Range' and a click event.

xml code

Step 3

Write the following code for the button click event.

  • Create an object of "Random' class.
  1. Random r = new Random();  
  • To get the next value of the random object, pass the textbox's value as a range after the integer conversion in the Next() method and save the output in an int variable named "num'.
  1. int num=r.Next(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));  
  • Print the "num' variable.
  1. Response.Write(num.ToString());  

csharp code image

Step 4

After running the page:

local host
Set some int value in both textboxes, like I have set 100 to 300 as the range.

local numbers
Notes
  • The maximum value should be greater than the minimum value, otherwise you will get an exception.
  • You can only send int values, nothing else.
  • You can also set only a minimum value without a maximum value.
After clicking the button, first I got the "285" as the random number.

random number

And the second time, I got "199" as the random number.

local input 

Up Next
    Ebook Download
    View all
    Learn
    View all