I want to generate non-repeated random number.
I tried the following code but it generates repeated random number.

``````protected void Button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int n = rnd.Next(1, 100);
Label1.Text = n.ToString ();
}``````

## All 4 Replies

``````int []ar={1,2,3,4,5,,...100},i,j,temp,m;
Random rnd = new Random();
for(m=1;m<=20;m++) {
i = rnd.Next(1, 100);
j = rnd.Next(1, 100);
temp=ar[i]; ar[i]=ar[j]; ar[j]=temp;
}
. ...``````

Thanx adapost 4 ur attention,but pls explain this code for non-repeated random number.

Exchange a number at two random indexes.

I seen this thread a few days ago and wanted to answer it but didn't have the time. While the answer you got is very good there are other ways of doing this. One of the ways is using a generic list and generics is something that you should learn.

Make sure you call "using System.Collections.Generic;" at the top of your page.
You can see below that the first thing I did was to create the generic list from 1 to 100 or is that 99 LOL. the next thing I did was to randomly pick a number then I put that number in a label. I then removed that number from the generic list so there is no way that I can randomly pick the same number more then one time. I run the loop 50 time just to play with it. Try generic I think once you get the hang of generic you will like it.

``````protected void Button1_Click(object sender, EventArgs e)
{
List<int> myNumbers = new List<int>();
for (int i = 1; i < 100; i++)
{
}

Random number = new Random();

for (int i = 0; i < 50; i++)
{
int n = number.Next(0, myNumbers.Count);
Label1.Text += "<br />" + myNumbers[n].ToString();
myNumbers.RemoveAt(n);
}
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.