emmer
emmer

Reputation: 33

writing c# for loop to page

I'm trying to learn C#. A lot of the tutorials I've found write to the console, but I'd like to practice it in the context of a web app, and write my results to the page in some kind of control (literal, label, or something). I'm starting out with a simple FizzBuzz program, but for some reason it's only printing the last number in the loop (99). Any ideas how I can write out each iteration to the page? Thanks in advance

My code:

<asp:Literal ID="myLit" runat="server"></asp:Literal>

namespace practice
{
    public partial class fizzbuzz_csharp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                myLit.Text = i.ToString();
            }
        }
    }
}

Upvotes: 1

Views: 258

Answers (4)

Raghavan
Raghavan

Reputation: 637

Change inside of the loop to

myLit.Text += i.ToString() + "<br />";

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

You are always overwriting the Text property of the Literal control in the loop. That's why you only see the last. You could use a ListBox instead:

for (int i = 0; i < 100; i++)
{
    myListBox.Items.Add(i.ToString());
}

You could also append <br /> to wrap each line, although it's not good practise in web.

for (int i = 0; i < 100; i++)
{
    myLit.Text += i.ToString() + "<br />";
}

Upvotes: 3

lboshuizen
lboshuizen

Reputation: 2786

You are writing the text directly to the control and not appending it. At the end of the loop al previous values are overwritten and only the last one is shown

Change it to

MyLit.Text += i.ToString + "<BR />"

Upvotes: 5

Stuart Golodetz
Stuart Golodetz

Reputation: 20656

You're overwriting myLit.Text on each iteration of the loop, so its final value is "100". You want to append to myLit.Text instead. For efficiency, this is probably best done by using something like a System.Text.StringBuilder and then assigning the final result to myLit.Text.

Upvotes: 2

Related Questions