I am making a Windows Form app in C#. I need to print an array with random numbers on the screen.
There are 20 numbers in total (0 till 19). But it only prints the 19th element. Can anyone help me out? (See image) Don't worry about the comparison number. I just want to print all arrays in the label in the form. Here is some code:
const int numberOfItems = 20;
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
beforeLoop.Text = $"Element {i} = {numbers[i]}";
total += numbers[i];
}
}
private void compare_Click(object sender, EventArgs e)
{
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
int numberBigger = numbers[i] + 10;
int numberSmaller = numbers[i] - 5;
total += numbers[i];
int number = int.Parse(numberBox.Text);
if (number > numbers[i])
{
printLabel.Text = $"Element {i} = {numberBigger}";
}
else
{
printLabel.Text = $"Element {i} = {numberSmaller}";
}
}
}

beforeLoop.Text. Since your computer is probably quite fast, shouldn't it be obvious that you will only see the result of the final assignment?TextProperty which is overwriting any previously set values. Try using "+=" instead of just "=" and see if that works. You may also need a "new line" character (trySystem.Environment.NewLine) at the end to put each "Element" on its own line.compare_Clickmethod. Ideally even removingforloop and replacing it with two assignments likestring s = "a"; s = "b";and question like "where 'a' goes after the second assignment".beforeLoop.Text = $"Element {i} = {numbers[i]}";. Did you want to use a multiline textbox, or a listbox or some other control to display multiple lines of text.