Thursday, 3 April 2014

C#.NET, ASP.NET - Generate non repeated random numbers in C#.NET within the range with the help of Random class.

Hi All,
In this article I will show you how to generate a non repeated random number in between specified range step by step with the explination of code in C#.NET with the help of ASP.NET page.

First please have a look at the complete script page and code behind file.


Generate-Random-Number.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Generate-Random-Number.aspx.cs" Inherits="Scripts_MAR_RandomNumber" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        table tr td:first-child
        {
            width: 45px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        Enter Number: 
        <table class="auto-style1">
            <tr>
                <td>From:</td>
                <td>
                    <asp:TextBox ID="txtFrom" MaxLength="4" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>To:</td>
                <td>
                    <asp:TextBox ID="txtTo" MaxLength="4" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblStatus" runat="server" ForeColor="Red" Text=""></asp:Label>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:TextBox ID="txtRandomNumbers" TextMode="MultiLine" runat="server" Height="113px" Width="434px"></asp:TextBox>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Generate-Random-Number.aspx.cs

using System;
using System.Collections.Generic;
using System.Text;

public partial class Scripts_MAR_RandomNumber : System.Web.UI.Page
{
    
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        // Check the From and To fields have a valid numeric numbers.
        if (IsValidForm())
        {
            // Generate Random Numbers.
            var randomNumers = GenerateRandomNumbers(Convert.ToInt32(txtFrom.Text), Convert.ToInt32(txtTo.Text));

            // Write random numbers to TextBox.
            PrintRandomNumbers(randomNumers);
        }
    }

    // Method to write non repeated random numbers to the TextBox.
    private void PrintRandomNumbers(List<int> randomNumers)
    {
        // Create a StringBuilder to hold the random numbers.
        var sbNumbers = new StringBuilder();
        foreach (var number in randomNumers)
        {
            // Add random numbers from List to StringBuilder.
            sbNumbers.Append(number + ", ");
        }

        // Write random numbers from StringBuilder to TextBox
        txtRandomNumbers.Text = sbNumbers.ToString();
    }

    // Method to generate non repeat random numbers.
    private List<int> GenerateRandomNumbers(int minValue, int maxValue)
    {
        // Create an instance of Random class.
        var randGenerator = new Random();

        // Create an instance of List<int> to store random numbers.
        var randValues = new List<int>();

        int randNum = 0;

        for (int value = minValue; value <= maxValue; value++)
        {
            // Generate a new random number between range (Min, Max). 
            randNum = randGenerator.Next(minValue, maxValue + 1);

            // Check if the new generated random number is existed in List.
            while (randValues.Contains(randNum))
            {
                // If the the number exists generate new random number with in the range (Min, Max).
                randNum = randGenerator.Next(minValue, maxValue + 1);
            }

            // Add non repeated random number to the List
            randValues.Add(randNum);
        }

        // Return non repeated random numbers List.
        return randValues;
    }

    // Method to check the values are entered in the From field and To field are numeric are not.
    private bool IsValidForm()
    {
        var validForm = true;
        int value = 0;

        // Check From value is empty or not.
        if (string.IsNullOrWhiteSpace(txtFrom.Text))
        {
            validForm = false;
            lblStatus.Text = "Please enter From value.";
        }
        else
            // Check From value is integer or not.
            if (!int.TryParse(txtFrom.Text, out value))
            {
                validForm = false;
                lblStatus.Text = "Please enter valid numeric value in From field.";
            }
            else
                // Check From value is negative or not.
                if (Convert.ToInt32(txtFrom.Text) < 0)
                {
                    validForm = false;
                    lblStatus.Text = "Please enter positive value in From field.";
                }
        // If the value entered in From field is valid then check for To value.
        if (validForm)
        {
            // Check To value is empty or not.
            if (string.IsNullOrWhiteSpace(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "Please enter To value.";
            }
            else
                // Check To value is integer or not
                if (!int.TryParse(txtTo.Text, out value))
                {
                    validForm = false;
                    lblStatus.Text = "Please enter valid numeric value in To field.";
                }
                else
                    // Check To value is negative or not
                    if (Convert.ToInt32(txtTo.Text) < 0)
                    {
                        validForm = false;
                        lblStatus.Text = "Please enter positive value in To field.";
                    }
        }
        // If both From and To fields are integers then check for "From value < To value"
        if (validForm)
        {
            if (Convert.ToInt32(txtFrom.Text) >= Convert.ToInt32(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "From value should be less than To value.";
            }
        }
        if (validForm)
        {
            if (Convert.ToInt32(txtTo.Text) < Convert.ToInt32(txtFrom.Text))
            {
                validForm = false;
                lblStatus.Text = "To value should be greater than From value.";
            }
        }

        // Return the form is valid or invalid.
        return validForm;
    }
}


Step By Step Explanation:

1. Create an interface with two TextBoxes and one Button as shown in the Script page.

2. In the Button click event write the following code.
protected void btnGenerate_Click(object sender, EventArgs e)
    {
        // Check the From and To fields have a valid numeric numbers.
        if (IsValidForm())
        {
            // Generate Random Numbers.
            var randomNumers = GenerateRandomNumbers(Convert.ToInt32(txtFrom.Text), Convert.ToInt32(txtTo.Text));

            // Write random numbers to TextBox.
            PrintRandomNumbers(randomNumers);
        }
    }
The above Button click code is using 3 different methods to process different actions.

3. Write a method IsValidForm() to check the form fields are satisfying the following conditions. -  Check From value is empty or not.
-  Check From value is integer or not.
-  Check From value is negative or not.
-  If the value entered in From field is valid then check for To value.
-  Check To value is empty or not.
-  Check To value is negative or not
-  If both From and To fields are integers then check for "From value < To value"
-  Return the form is valid or invalid.

// Method to check the values are entered in the From field and To field are numeric are not.
    private bool IsValidForm()
    {
        var validForm = true;
        int value = 0;

        // Check From value is empty or not.
        if (string.IsNullOrWhiteSpace(txtFrom.Text))
        {
            validForm = false;
            lblStatus.Text = "Please enter From value.";
        }
        else
            // Check From value is integer or not.
            if (!int.TryParse(txtFrom.Text, out value))
            {
                validForm = false;
                lblStatus.Text = "Please enter valid numeric value in From field.";
            }
            else
                // Check From value is negative or not.
                if (Convert.ToInt32(txtFrom.Text) < 0)
                {
                    validForm = false;
                    lblStatus.Text = "Please enter positive value in From field.";
                }
        // If the value entered in From field is valid then check for To value.
        if (validForm)
        {
            // Check To value is empty or not.
            if (string.IsNullOrWhiteSpace(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "Please enter To value.";
            }
            else
                // Check To value is integer or not
                if (!int.TryParse(txtTo.Text, out value))
                {
                    validForm = false;
                    lblStatus.Text = "Please enter valid numeric value in To field.";
                }
                else
                    // Check To value is negative or not
                    if (Convert.ToInt32(txtTo.Text) < 0)
                    {
                        validForm = false;
                        lblStatus.Text = "Please enter positive value in To field.";
                    }
        }
        // If both From and To fields are integers then check for "From value < To value"
        if (validForm)
        {
            if (Convert.ToInt32(txtFrom.Text) >= Convert.ToInt32(txtTo.Text))
            {
                validForm = false;
                lblStatus.Text = "From value should be less than To value.";
            }
        }
        if (validForm)
        {
            if (Convert.ToInt32(txtTo.Text) < Convert.ToInt32(txtFrom.Text))
            {
                validForm = false;
                lblStatus.Text = "To value should be greater than From value.";
            }
        }

        // Return the form is valid or invalid.
        return validForm;
    }
4. Write a method GenerateRandomNumbers(int minValue, int maxValue) to generate the non repeated random numbers with the following the steps.
- Create an instance of Random class.
- Create an instance of List<int> to store random numbers.
- Generate a new random number between range (Min, Max). 
- Check if the new generated random number is existed in List.
- If the the number exists generate new random number with in the range (Min, Max).
- Add non repeated random number to the List
- Return non repeated random numbers List.

// Method to generate non repeat random numbers.
    private List<int> GenerateRandomNumbers(int minValue, int maxValue)
    {
        // Create an instance of Random class.
        var randGenerator = new Random();

        // Create an instance of List<int> to store random numbers.
        var randValues = new List<int>();

        int randNum = 0;

        for (int value = minValue; value <= maxValue; value++)
        {
            // Generate a new random number between range (Min, Max). 
            randNum = randGenerator.Next(minValue, maxValue + 1);

            // Check if the new generated random number is existed in List.
            while (randValues.Contains(randNum))
            {
                // If the the number exists generate new random number with in the range (Min, Max).
                randNum = randGenerator.Next(minValue, maxValue + 1);
            }

            // Add non repeated random number to the List
            randValues.Add(randNum);
        }

        // Return non repeated random numbers List.
        return randValues;
    }
5. Write a method  PrintRandomNumbers(List<int> randomNumers) to print the values in TextBox.
- Create a StringBuilder to hold the random numbers.
- Add random numbers from List to StringBuilder.
- Write random numbers from StringBuilder to TextBox

// Method to write non repeated random numbers to the TextBox.
    private void PrintRandomNumbers(List<int> randomNumers)
    {
        // Create a StringBuilder to hold the random numbers.
        var sbNumbers = new StringBuilder();
        foreach (var number in randomNumers)
        {
            // Add random numbers from List to StringBuilder.
            sbNumbers.Append(number + ", ");
        }

        // Write random numbers from StringBuilder to TextBox
        txtRandomNumbers.Text = sbNumbers.ToString();
    }
6. Run the page and test the page by giving the following values in From field and To field.
From: 1
To: 10
From: 1
To: 100

Output: 


No comments: