How to generate random no in C#.Net


In my previous article I have explained about How to How to Automatically change the version of css and js files in Asp.Net | C#.Net. In this article I am going to explain about how to generate random numbers using C#.Net.

Random class in System namespace is used to  generate pseudo-random number within the specified range. For explanation purpose i have a label to show the generated random no and a button to generate the random no.

By default while loading the form itself random no will be generated and shown in the label. And if you click the Generate button then it will generate the random no and show it in the label. 

Below is the aspx code
<form id="form1" runat="server">
<div style="margin: 100px;">
    Random No between 1 to 10000
    <br />
    <asp:Label ID="lblRandomNo" runat="server" Style="color: Red;" />
    <br />
    <asp:Button ID="btnRandom" runat="server" Text="Renerate" OnClick="btnRandom_Click" />

Below is the cs code
protected void Page_Load(object sender, EventArgs e)
protected void btnRandom_Click(object sender, EventArgs e)
private void GenerateRandomNo()
    Random objRand = new Random();
    int nextRandomNo = objRand.Next(1, 10000);
    lblRandomNo.Text = nextRandomNo.ToString();

Sample output will be

generate random numbers in C#.Net

Do you like this article? Help us to improve. Please post your comments below.


Post a Comment

Online Casino