Generate 10 (ten) unique random numbers using C# and VB.Net in Windows Application

Last Reply 22 days ago By dharmendr

Posted 23 days ago

Dear Team,

I want to generate 10 randam no in 10 text between range of 1 to 10 in C# Windows Form.

can some one help me.

Posted 22 days ago Modified on 10 days ago

Hi gmrneeraj,

Refer below code.

Code

C#

protected void Form_Load(object sender, EventArgs e)
{
    int min = 1;
    int max = 10;
    int total = 10;
    List<int> ids = GenerateRandom(min, max, total);
    lblNumbers.Text = string.Join(", ", ids));
}

private List<int> GenerateRandom(int minRange, int maxRange, int total)
{
    Random random = new Random();
    int count = 0;
    List<int> numbers = new List<int>();
    List<int> listMunbers = new List<int>();
    for (int i = 0; i < total; i++)
    {
        listMunbers.Add(i);
    }
    while (listMunbers.Count > 0)
    {
        int number = random.Next(minRange, maxRange + 1);
        if (!numbers.Contains(number) && listMunbers.Count > 0)
        {
            numbers.Add(number);
            listMunbers.Remove(count);
            count++;
        }
    }

    return numbers;
}

VB.Net

Protected Sub Form_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    Dim min As Integer = 1
    Dim max As Integer = 10
    Dim total As Integer = 10
    Dim ids As List(Of Integer) = GenerateRandom(min, max, total)
    lblNumbers.Text = String.Join(", ", ids)
End Sub

Private Function GenerateRandom(ByVal minRange As Integer, ByVal maxRange As Integer, ByVal total As Integer) As List(Of Integer)
    Dim random As Random = New Random()
    Dim count As Integer = 0
    Dim numbers As List(Of Integer) = New List(Of Integer)()
    Dim listMunbers As List(Of Integer) = New List(Of Integer)()
    For i As Integer = 0 To total - 1
        listMunbers.Add(i)
    Next
    While listMunbers.Count > 0
        Dim number As Integer = random.Next(minRange, maxRange + 1)

        If Not numbers.Contains(number) AndAlso listMunbers.Count > 0 Then
            numbers.Add(number)
            listMunbers.Remove(count)
            count += 1
        End If
    End While

    Return numbers
End Function