Reputation: 13
I'm having trouble randomizing X-amounts of strings and adding them to my listbox
. it keeps adding the same string over and over. i want it to add 1 line per string. if i say that amount is 11, it just makes one string and adds it 11 times to listbox
. what am i doing wrong?
here is my code:
for (int i = 0; i < amount; i++)
{
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int t = 0; t < 8; t++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[a-z0-9]")) ;
rndString += c;
}
listBox1.Items.Add(rndString);
}
Upvotes: 0
Views: 222
Reputation: 4895
Random adomRng = new Random();
for (int i = 0; i < amount; i++)
{
string rndString = string.Empty;
char c;
for (int t = 0; t < 8; t++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[a-z0-9]")) ;
rndString += c;
}
listBox1.Items.Add(rndString);
}
Put the random
init code outside of the loop, it will get you the correct result
Explanation: creating multiple new random objects in the short period of time (let's say inside a for loop) will always give you the same output because it will use the current timestamp as random seed.
Upvotes: 2
Reputation: 29026
You are almost there,just make two simple changes in your code to achieve the target:
for (int t = 0; t < 8; t++)
{
rndString =""; //Change 1
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[a-z0-9]")) ;
rndString += c;
listBox1.Items.Add(rndString);// change 2
}
Upvotes: 0