在c#中显示带有换行符的标签文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13878347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display label text with line breaks in c#
提问by Developer
Is it possible to display the label text with line breaks exactly as per the image
是否可以完全按照图像显示带有换行符的标签文本


I need the text on the label to be printed exactly can some one help me, my desired text that has to be shown on the label will be stored in a string-builder
我需要准确打印标签上的文本,有人可以帮助我,我需要在标签上显示的文本将存储在字符串生成器中
采纳答案by Habib
You may append HTML <br />in between your lines. Something like:
您可以在行<br />之间附加 HTML 。就像是:
MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text";
With StringBuilderyou can try:
使用StringBuilder,您可以尝试:
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />");
回答by Dev
You can also use <br/>where you want to break the text.
您还可以使用<br/>要中断文本的位置。
回答by Vishal Suthar
You can use <br />for Line Breaks, and for white space.
您可以<br />用于换行符和 空白。
string s = "First line <br /> Second line";
Output:
输出:
First line
Second line
For more info refer to this: Line break in Label
有关更多信息,请参阅:标签中的换行符
回答by Duk
Also you can use the following
您也可以使用以下
@"Italian naval...<br><br>"+
Above code you can achieve double space. If you want single one means you simply use
.
上面的代码可以实现双倍空间。如果您想要单个意味着您只需使用
.
回答by MobileMon
I had to replace new lines with br
我不得不用 br 替换新行
string newString = oldString.Replace("\n", "<br />");
or if you use xml
或者如果你使用 xml
<asp:Label ID="Label1" runat="server" Text='<%# ShowLineBreaks(Eval("Comments")) %>'></asp:Label>
Then in code behind
然后在后面的代码中
public string ShowLineBreaks(object text)
{
return (text.ToString().Replace("\n", "<br/>"));
}
回答by Adam Scharp
I know this thread is old, but...
我知道这个线程很旧,但是...
If you're using html encoding (like AntiXSS), the previous answers will not work. The break tags will be rendered as text, rather than applying a carriage return. You can wrap your asp label in a pre tag, and it will display with whatever line breaks are set from the code behind.
如果您使用 html 编码(如AntiXSS),则先前的答案将不起作用。中断标记将呈现为文本,而不是应用回车符。你可以将你的 asp 标签包装在一个 pre 标签中,它会显示任何从后面的代码中设置的换行符。
Example:
例子:
<pre style="width:600px;white-space:pre-wrap;"><asp:Label ID="lblMessage" Runat="server" visible ="true"/></pre>
回答by Hajir
Or simply add one line of:
或者简单地添加一行:
Text='<%# Eval("Comments").ToString().Replace("\n","<br />") %>'

