Introduction
Sometimes developers need to generate random numbers and for this you use Random class in C# that resides in the "System" namespace.
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'.
And add the Web form named "Deafult.aspx' into it.
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.
Step 3
Write the following code for the button click event.
- Create an object of "Random' class.
- 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'.
- int num=r.Next(Convert.ToInt32(TextBox1.Text), Convert.ToInt32(TextBox2.Text));
- Print the "num' variable.
- Response.Write(num.ToString());
Step 4After running the page:
Set some int value in both textboxes, like I have set 100 to 300 as the range.
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.
And the second time, I got "199" as the random number.