Generating Random Numbers Using ASP.NET C#

Introduction

In this article I have explained the C# Random function which is  used in an ASP.Net application so let us start with the basics to ensure this article is understandable for beginners too.
 
What is Random Number?
 
A number that has no specific sequence which is changed dynamically with the given range in the Random function each time it is generated is called a Random number. 
 
So I hope you understand the concept of random numbers. Now we will create the application for demonstrating the use of the Random function.
 
Now let us start to create a Website as:
  1. Start - All Programs - Microsoft Visual Studio 2010.
  2. File - New Website - C# - Empty website (to avoid adding a master page).
  3. Give the web site a name such as Generate_RandomNumbres or another as you wish  and specify the location.
  4. Then right-click on Solution Explorer - Add New Item - Default.aspx page.
  5. Drag and drop one button to generate a random number and one label to show the generated random numbers in the <form> section of the Default aspx page.
The Default.aspx page's <form> section should look as:
 
<formid="form1"runat="server">
        <asp:Button id ="Button1" runat ="server"Text="Generate number " onclick="Button1_Click" />
        <p
            <asp:Label id ="Label1"runat ="server" Text ="Label"></asp:Label></p>
    </
form >

Switch the view code and create the Random () object in the partial class as:
 
static Random random = new Random();
 
Then double-click on the button and use the following code in the button click event as:
 
 protectedvoid Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 2; i++) 
        {
           
            Label1.Text ="The generated Random number is " + (Convert.ToString(random.Next(10, 200))); // to specify range for random number
        }
 
In the above for loop body random.Next(10, 200) is a function which specifies the range of random numbers to be generated; in other words it will generate numbers in the range 10 to 200.
 
Now run the application and click on the Generate number button which generates the number 186 on the first click as shown in the following image:
 
Firstclick.png
 
Click on second time on generate button, it will generate the number 73 as shown in the following image:
 
secondclick.png
 
Similarly, click on N numbers at a time and it will generate various random numbers with no specific sequence and for moves the loop between the random function specified range 10 to 200. 
 
Summary
 
So by all the examples above I have explained how to use the Random function of C#. You can implement it as you want according to your application requirements. If you have suggestions regarding this article then please contact me.


Similar Articles