How to Generate Random Numbers in C# and ASP.NET

Sometimes developers need to generate random numbers in a Web page or website. This article demonstrates how to create a simple Web page using ASP.NET and generates and displays a random number using the Random class available in C# and .NET. 
 
For generating a random number, you can use the Random class in C# that resides in the "System" Namespace.
 
Random 

 

Random
 
Step 1: Create a new Empty Website named "Website1" using Visual Studio.
 
new Empty Website
 
And add the Web form named "Deafult.aspx" into it.
 
Web form
 
Step 2: Add a button to the "Deafult.aspx" page with the Text "Generate Random Number" and a click event.
 
Deafult
 
Step 3: Write the code on button click event.
 
Create an object of the "Random" class. 
  1. Random r = new Random();  
To get the next value of the random object and save the output in an int variable named "num". 
  1. int num=r.Next();  
  2. Print the "num" variable.  
  3. Response.Write(num.ToString());  
 num
 
Step 4: After running the page.
 
running the page 
After clicking the button, first I got "369593053" as the random number.
 
And the second time, I got "820031117" as the random number.

 The name of a character array is actually a pointer to the first element of the array.

The name of a character array is actually a pointer to the first element of the array.
 
Note: You can also set the range of random numbers. In my future article you can see that.
 
Summary
 
In this article, I demonstrates how to create a simple one page Website that uses and displays a random number. 


Similar Articles