Jumat, 03 Januari 2014

Computer Programming : How to Generate random number in ASP.NET, Example

You can generate random number using Random class. According to msdn library:
Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.
A Random class exists in System namespace, used to display pseudo-random numbers. The Class has many methods, such as Next() method. Overloaded Next method take different parameters such as zero argument, one argument and two argument.

Random class instance . Next () : Following Code gives Non-negative integer number like 1 to further.
Random class instance . Next (Int32) : You can specify a number, which is maximum for generated output.
Random class instance . Next (Int32, Int32): You can specify minimum and maximum number in parameter, following output generated between specified argument.

Application

  1. Mathematical CAPTCHA Design
  2. Kids Game.

Lets take an simple example

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Random Number</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Height="37px" onclick="Button1_Click" 
            Text="Random Number " />
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Random r1 = new Random();
        string s = r1.Next(10, 100).ToString ();
        Label1.Text = s;


    }

}


Code generate following output

Computer Programming : How to Generate random number in ASP.NET, Example

Computer Programming : How to Generate random number in ASP.NET, Example
      

Tidak ada komentar:

Posting Komentar