C# 如何在多行文本框中添加文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/927679/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:24:44  来源:igfitidea点击:

How to add text in a multiline textbox?

c#

提问by

I have to add details of my file into a multiline textbox. But all the details are getting added in a single line in the text box and not in a vertical sequence. I used Environment.NewLine and also used "\r\n", but it's not of any help. I have ticked the multiline text box in a Windows Forms form and also set it to true but to no avail.

我必须将文件的详细信息添加到多行文本框中。但是所有细节都添加到文本框中的一行中,而不是按垂直顺序添加。我使用了 Environment.NewLine 并使用了 "\r\n",但它没有任何帮助。我在 Windows 窗体窗体中勾选了多行文本框并将其设置为 true 但无济于事。

My line of code is like this:

我的代码行是这样的:

m_Txt.Multiline = true;

m_Txt.Text = fileInfo.m_Title + "\r\n" + 
             fileInfo.m_Identifier + Environment.NewLine + 
             fileInfo.m_TotalTime;

回答by JasonRShaver

Shift+Enter

Shift+Enter

In the Visual Studio resource editor, you can hit "Shift + Enter" 
to create a new line, as doing something like "\r\n" will get escaped 
out.  You will also need to increase the cell height to see both 
lines as it does not auto-size.

回答by BlackWasp

Not sure why your code would not work unless something else is going on.

不知道为什么除非发生其他事情,否则您的代码将无法工作。

I just created a WinForms project using C#, added a textbox, set it multiline and added the following code - works a charm.

我刚刚使用 C# 创建了一个 WinForms 项目,添加了一个文本框,将其设置为多行并添加了以下代码 - 很有魅力。

textBox1.Text = "a\r\nb";

回答by Chris Doggett

If you're doing it programatically, append the new line to m_Txt.Lines, which is a string[].

如果您以编程方式执行此操作,请将新行附加到 m_Txt.Lines,它是一个 string[]。

m_Txt.Lines = new string[]{ fileInfo.m_Title, fileInfo.m_Identifier, fileInfo.m_TotalTime};

回答by Falconeer

A cleaner answer is:

更简洁的答案是:

Assuming txtStatus is a textbox:

假设 txtStatus 是一个文本框:

txtStatus.Multiline = True;
txtStatus.Clear();
txtStatus.Text += "Line 1" + Environment.NewLine;
txtStatus.Text += "Line 2" + Environment.NewLine;

Using the built in enumeration means cleaner code.

使用内置枚举意味着更简洁的代码。

回答by Gustavo Massaneiro

I just wrote this code, seems to be working fine.

我刚刚写了这段代码,似乎工作正常。

public void setComments(String comments)
        {
            String[] aux;
            if(comments.Contains('\n')) //Multiple lines comments
            {
                aux = comments.Split('\n');
                for (int i = 0; i < aux.Length; i++)
                    this.textBoxComments.Text += aux[i] + Environment.NewLine;  
            }
            else //One line comments
                this.textBoxComments.Text = comments;
        }