C# TextBox换行[huan hang]时你往往会想到直接付给一个含有换行[huan hang]符"\n"的字符[zi fu]串[zi fu chuan]给Text属性[shu xing]:

 aTextBox.Text = "First Line\nSecond Line\nThird Line";  

可是实际运行[yun hang]的时候你却发现它始终不会换行[huan hang],显示[xian shi]的结果为"First LineSecond LineThirdLine"。

其实主要是因为C# TextBox换行[huan hang]运行[yun hang]在Windows上。Windows能够显示[xian shi]的换行[huan hang]必须由两个字符[zi fu]组成:carriage return & line feed,也就是必须是"\r\n"。如果只是"\n"在Windows中不能显示[xian shi]为换行[huan hang]的,这与Linux/Unix等其他的操作系统[xi tong][cao zuo xi tong]不一样。所以上边如果把"\n"替换[ti huan]成"\r\n"就可以了。

其实问题[wen ti]仍然没有很好的解决,因为用"\r\n"能够满足Windows的要求了,但是如果是其他平台[ping tai]怎么办?为了要确保[que bao]让换行[huan hang]效果在各种平台[ping tai]上都能够正常的显示[xian shi],请用Environment.NewLine。它可以确保[que bao]在不同的平台[ping tai]下都能够返回正确的换行[huan hang]字符[zi fu],在Windows下是\r\n,在Linux(Mono)下就应该是\n了。 所以上面的代码[dai ma]应该写成:

 aTextBox.Text = "First Line" + Environment.NewLine + "Second Line" + Environment.NewLine + "Third Line";  

posted on 2015-10-23 09:40  王庆东mas  阅读(6491)  评论(0编辑  收藏  举报