Hello I am new to WPF and i do have some experience in ASP.NET but this is totally new like, labels I would be doing label.Content instead of label.Text, anyways.. I am trying to do a simple form, where upon clicking the buton it shows 5 different random numbers..
When I debug this code line by line, it does randomize and has a string of different numbers but when i do not debug and run it at once and click the button it shows the same number for all? , not sure why… so ideally i would have
[1] [23] [45] [24] [34]
It gives me that result if I debug and step through but if I do not debug and just run the program i get
[23] [23] [23] [23] [23]
Any help would be much appreciated
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
int[] numbers = new int[5];
StringBuilder sb = new StringBuilder();
List<int> nums = new List<int>();
foreach (int i in numbers)
{
int rand = RandomNumber(1,59);
nums.Add(rand);
}
string numsList = string.Empty;
foreach (int items in nums)
{
numsList += "[" + items.ToString() + "]";
}
lblNumber.Content = numsList.ToString();
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
}
You should not create a new
Randomevery time (make it a readonly field instead). The seed may always be the same otherwise when creating new instances shortly one after another. It only works in debug mode since the instances are created more slowly when you step through.MSDN: