Is there a way to preserve formatting when outputing to a label?
I have some user input that I am outputting to a label.
I have used HTML.Encode in order to show the input in the way the user entered it (ignoring as a html tag).
However, I have noticed that the user input like New Line are not using in the label. It's simply displayed as white space.
I've done this
msg.Text = msg.Text.Replace(Environment.NewLi开发者_JAVA百科ne, "<br />");
which seems to now be displaying the right input.
Is that the best way to do this? Or is there like a common method that can convert newLines, tabs, etc. all of the invisible formatting things into HTML tags?
I don't know of any other way. What I usually do (in case you have a single "\n" or a "\r\n" combo) is replace all "\r\n" first, then any single "\n" last.
lbl.Text = lbl.Text.Replace("\r\n", "<br />").Replace("\n", "<br />");
For tabs you can use 4 non-breaking spaces.:
lbl.Text = lbl.Text.Replace("\t", " ")
To preserve any spacing (as html will aggregate multiple continuous spaces into a single space) use:
lbl.Text = lbl.Text.Replace(" ", " ")//Replace every 2-space pair.
Remember to Encode your text first before adding in markup like <br /> that you intentionally want to render.
You could also use a TextBox, set it's MultiLine property to "true" and Enabled to "false" if you want to display the information with the original carriage returns without resorting to inserting markup. I think the label is the best choice though.
If possible, just use a Multiline Textbox instead of label.
精彩评论