user3303264
user3303264

Reputation: 1

Trying to format output from a for loop into a label

I'm sure there's a simple answer to this but I'm trying to make a header using a for loop. My variable tipRate is set at .10 and TIPSTESP is .05. The for loop works fine with a Console.WriteLine command in a console app, but I'm trying to do this in a form. The output should be .10 .15 .20 .25. I'm not sure how to append the string to keep it from writing over the previous output. Thanks in advance.

for (tipRate = lowRate; tipRate <= highRate; tipRate += TIPSTEP)
    lblTipHead.Text = String.Format( "{0,  8}", tipRate.ToString("F"));

Upvotes: 0

Views: 79

Answers (3)

J0e3gan
J0e3gan

Reputation: 8938

You need to use += to append to the current value of lblTipHead.Text rather than destructively assign to it - in other words...

lblTipHead.Text += String.Format( "{0,  8}", tipRate.ToString("F"));

...instead of:

lblTipHead.Text = String.Format( "{0,  8}", tipRate.ToString("F"));

With +=, the statement translates to:

lblTipHead.Text = lblTipHead.Text + String.Format( "{0,  8}", tipRate.ToString("F"));

Upvotes: 0

Josh Anderson
Josh Anderson

Reputation: 438

You are replacing the label text every time, use += instead of =

lblTipHead.Text += " " + String.Format( "{0,  8}", tipRate.ToString("F"));

You should also probably clear the label text before running the loop, just to be sure you aren't appending unwanted data, this will clear the label lblTipHead.Text = ""

Upvotes: 0

Tarec
Tarec

Reputation: 3255

lblTipHead.Text += " " + String.Format( "{0,  8}", tipRate.ToString("F"));

Also, lblTipHead.Text = String.Empty; before the loop. However it's a better practice to create a string first (or a StringBuilder using Append() method), concatenate your values and then assign it to lblTipHead.Text, which will prevent unneeded form refreshing.

Let me know if that's helpfull.

Upvotes: 1

Related Questions