Hellow everybody!
I just have a simple but very stupid problem.. I'm writing a windows forms applicaton that generates random letters and put them in the form's label control.
private void OnStart(object sender, EventArgs e) //Event when you click on button 'Start'
{
//timer1.Start();
String[] text=new String[4];
for (int i = 0; i < 4; i++)
{
int number = GenerateNumber(1, 25); //1 and 25 are max and min
text[i] = GetLetter(number); //Function that returns a letter(type is String) and it works OK
//MessageBox.Show("Letter: " + text[i]);
}
label1.Text = text[0]+text[1]+text[2]+text[3];
}
And here is the problem: In the label1 control i get four(4) letters which are the same(example: RRRR). Now if I only change this:
private void OnStart(object sender, EventArgs e) //Event when you click on button 'Start'
{
//timer1.Start();
String[] text=new String[4];
for (int i = 0; i < 4; i++)
{
int number = GenerateNumber(1, 25); //1 and 25 are max and min
text[i] = GetLetter(number); //Function that returns a letter(type is String) and it works OK
MessageBox.Show("Letter: " + text[i]); //I changed only this line
}
label1.Text = text[0]+text[1]+text[2]+text[3];
}
Now I get four different letters(in the label1 control) which is OK(example: RSJK). Has anybody have any idea
what my problem is???
Loading

Ryan AlfordPosted Jan 22, 2009, 6:49 PM
Try this instead...
=============================
StringBuilder sb = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
sb.Append((char)rand.Next(65, 90));
}
label1.Text = sb.ToString();
=========================
jimmyPosted Jan 18, 2010, 10:55 PM
The real problem of your code is that the loop run very fast that actually your random number generator (that may use computer time or whatsoever) will give you the same number (because it is too fast). So when you put the MessageBox, this command will make the speed of the loop decreasing, and surely it will make the generator giving you different number.
That's the explanation of the problem occurs in your program. If you have time, you can try to remove the MessageBox and change it with a kind of delaying command available in C#, and definitely your program will work correctly.
Jozo HadziselimovichPosted Jan 22, 2009, 7:34 PM
Thanks again for that quick reply!! ...