Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this array in C# for a GUI, however is not displaying all the numbers, just the last one. Any ideas, please? Thanks

private void button4_Click(object sender, EventArgs e)
{
double[] BMI = {18.5,24.9,25,29.9,30};

for (int i = 0; i < BMI.Length; i++)
{
label10.Text = ($"{BMI[i]}");
}
}

What I have tried:

I have tried label10.Text = i.String and label10.Text = BMI.String
Posted
Updated 22-Jul-21 6:47am

It's only showing the last value because that's exactly what you told it to do. When you set the Text property of a control, you are telling it to replace the previous value with a new value, NOT append to the end of the text.

The TextBox will NOT update as you set new values. Since your code to change the Text property is running on the UI thread, the UI will not update (repaint) until the code goes back to idle, waiting for the user to click on something.

If you want to show each value in the loop, you have to move the method code to a background thread. You can use a BackgroundWorker[^] to do that.
 
Share this answer
 
Comments
CPallini 22-Jul-21 4:23am    
5.
Diasalva5 22-Jul-21 12:44pm    
Thanks, Dave!
As Dave says, a textbox only has one Text property, and if you overwrite it, you lose teh previous content.

If you want to display all the numbers in a single text box, then you either need to add a separator such as a comma or use a multiline textbox.
The separator is pretty simple:
C#
MyTextBox.Text = string.Join(", ", BMI);

But rather than use a multiline textbox, I'd suggest you use a data control such as a DataGridView which can display data in a tabular form.
 
Share this answer
 
Comments
CPallini 22-Jul-21 4:23am    
5.
Diasalva5 22-Jul-21 12:45pm    
Thank you, OriginalGriff!
I did as advised by OriginalGriff and it worked as expected,Thanks.

private void button4_Click(object sender, EventArgs e)
{
double[] BMI = {18.5,24.9,25,29.9,30};

for (int i = 0; i < BMI.Length; i++)
{

label10.Text = string.Join(" , ", BMI);
}
}
 
Share this answer
 
Comments
OriginalGriff 22-Jul-21 13:26pm    
No, you don't need the loop at all ...
Diasalva5 22-Jul-21 18:24pm    
Hello, OriginalGriff!
So, the loop is not needed?
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900