0

I just started with ASP.NET and I'm having trouble with displaying a result from a loop. For example:

int x = 0;
while (x < 10) {

  Label1.Text = x+""; // This will show only result 9 ( last result ). 
    x++;
}

How do I show all results instead of only one?

3

10 Answers 10

1

Instead of:

Label1.Text = x+"";

Do:

Label1.Text = Label1.Text + x;
Sign up to request clarification or add additional context in comments.

Comments

1

This will show only result 9 ( last result ).

Yes because you assign a new value to Label1.Text property in every iteration.

Try this instead;

int x = 0;
while (x < 10)
{

  Label1.Text = Label1.Text + x;
  x++;
}

Or instead define a string value outside of while and add it this int values inside of your loop and assign your .Text value outside of your loop like;

int x = 0;
string s = "";
while (x < 10)
{

  s += x;
  x++;
}
Label1.Text = s;

Or use StringBuilder would be better if you use a lot of numbers;

int x = 0;
StringBuilder s = new StringBuilder();
while (x < 10)
{

  s.Append(x);
  x++;
}
Label1.Text = s.ToString();

2 Comments

Do you really need to use a StringBuilder for an iteration of 10?
@huMptyduMpty For this case, no. But if OP uses a lot of string concatenations, StringBuilder is of course better..
0
int x = 0;

while (x < 10) {

  Label1.Text += x+""; // This will show "123456789". 
    x++;
}

You need to add to the text in each iteration.

Comments

0

If you want to show a list of them :

Label1.Text += "," + x.ToString();

Or

Label1.Text = Label1.Text + "," + x.ToString();

Either way will produce the result :

0,1,2,3,4,5,6,7,8,9

Comments

0

You should accumulate the values of each element, something like this:

int x = 0;
while (x < 10) {
  Label1.Text = Label1.Text + x;
  x++;
}

Comments

0
int x = 0;

while (x < 10) {

  Label1.Text += x.ToString();  
    x++;
}

1 Comment

You might improve this by adding a short comment to highlight the specific change.. for example, start off with "Use += to append:".
0

You could use string builder

try this:

 StringBuilder sb = new StringBuilder();
    int x = 0;

        while (x < 10) {
          sb.Append(x);
          sb.Append(" ");
            x++;
        }
 Label1.Text = sb.ToString(); 

Comments

0

Please use the code as below, you gotta assign a new id to Label1.Text in every iteration.

int x = 0;
    while (x < 10)
    {
        label1.Text += x.ToString();
        x++;

   }

Comments

0

Replace

Label1.Text = x+"";

with

  Label1.Text = Label1.Text + x.ToString();

Comments

0

+= append string to variable instead of replacing so,

int x = 0;
while (x < 10) {
  Label1.Text += x+" "; //append space to separate  
    x++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.