Wednesday, October 31, 2012

AppendLine method of StringBuilder class object doesn't work.

In ASP.NET AppendLine method of a StringBuilder class object does not put a new line if I show the result in asp:label control.

Here is the code snippet that I have tried - 



aspx page:-



<form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server">          </asp:Label>
    </div>
</form>

cs code:-



protected void Page_Load(object sender, EventArgs e)
    {

        StringBuilder output = new StringBuilder();

        string[] str = { "AB", "BC", "CD", "DE" };
        foreach (string s in str)
        {
            output.AppendLine(s);
        }
        lblResult.Text = output.ToString();

    }

Output:-

AB BC CD DE


I have tried Environment.NewLine also. but failed.


At last I have found the solution: <br/> - as HTML respects this tag only. neither \n nor \r\n



So, after correction the code

            output.Append(s + "<br/>");

I have got my desired Output:

AB
BC
CD
DE