C# 如何在文本框中使用 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1751371/
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
How To Use \n In a TextBox
提问by Nathan Campos
I'm developing a program that I'm using a string(generatedCode
) that contains some \n
to enter a new-line at the textBox that I'm using it(textBox1.Text = generatedCode
), but when I'm running the program, instead of breaking that line I'm seeing a square.
我正在开发一个程序,我正在使用一个字符串(generatedCode
),其中包含一些\n
在我使用它的文本框中输入一个新行(textBox1.Text = generatedCode
),但是当我运行该程序时,而不是打破该行我看到一个正方形。
Remember that I've set the Multiline
value of the textBox to True
.
请记住,我已将Multiline
textBox的值设置为True
.
采纳答案by Jon Skeet
Replace \n with \r\n - that's how Windows controls represent newlines (but see note at bottom):
用 \r\n 替换 \n - 这就是 Windows 控件表示换行符的方式(但请参阅底部的注释):
textBox1.Text = generatedCode.Replace("\n", "\r\n");
or
或者
textBox1.Text = generatedCode.Replace("\n", Environment.NewLine);
Note: As discussed in comments, you maywant to use Environment.NewLine
. It's unclear though - it's not well-defined what line separator Windows Forms controls should use when they're not running on Windows. Should they use the platform default, or the Windows one (as it's a port of a Windows GUI control)? One of the examples in MSDN doesuse Environment.NewLine
, but I've seen horribly wrong examples in MSDN before now, and the documentation just doesn't state which is should be.
注意:如评论中所述,您可能希望使用Environment.NewLine
. 但目前还不清楚 - 没有明确定义 Windows 窗体控件在不在 Windows 上运行时应使用的行分隔符。他们应该使用平台默认值还是 Windows 版本(因为它是 Windows GUI 控件的一个端口)?MSDN中的一个示例确实使用了Environment.NewLine
,但我之前在 MSDN中看到过非常错误的示例,文档只是没有说明应该使用哪个示例。
In an ideal world, we'd just have one line separator - and even in a second best world, every situation would clearly define which line separator it was expecting...
在理想的世界中,我们只有一个行分隔符 - 即使在第二好的世界中,每种情况都会清楚地定义它所期望的行分隔符......
回答by Bob
Usually \r\n
gets me a newline in a textbox. Try replacing your \n
with \r\n
just be careful you don't have a mix of \r\n
and \n
通常\r\n
让我在文本框中换行。尝试替换你\n
的\r\n
只是小心你没有混合\r\n
和\n
回答by MakoCSH
Add a carriage return (\r) and it should work:
添加回车(\ r),它应该可以工作:
TextBox1.Text = "First line\r\nSecond line";
回答by dancer42
since using \n is easier on the eyes (especailly when formatting), and also sometimes you don't control how the source string is constructed - I find best practice is to use:TextBox1.Text = str.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
因为使用 \n 更容易(尤其是在格式化时),而且有时您无法控制源字符串的构造方式 - 我发现最佳实践是使用:TextBox1.Text = str.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);