C#如何逐行读写多行文本框中的内容?

21

我有一个简单的程序,它有一个函数来从多行文本框中读取一行,当我按下按钮时。为了实现这个功能,我编写了以下代码:

TextReader read = new System.IO.StringReader(textBox1.Text);
int rows = 100;

string[] text1 = new string[rows];
for (int r = 1; r < rows; r++)
{
    text1[r] = read.ReadLine();
}

当点击button1时,代码将会如下所示:

textBox2=text1[1];

[1] 表示第一行。如何通过一次点击自动完成此操作?或者通过一次点击将第一行复制到textBox2,第二行到textBox3......等等。

请提供代码以及应将其放置的位置 ^_^

或者如果有其他方法也可以。

3个回答

31

属性 Lines 就在那里等着你了

if(textBox1.Lines.Length > 0)
    textBox2.Text=textBox1.Lines[0]; 

或者,将您的文本框按顺序放在一个临时数组中,并对它们进行循环(当然,我们应该始终检查textBox1中存在的行数)。

TextBox[] text = new TextBox[] {textBox2, textBox3, textBox4};
if(textBox.Lines.Length >= 3)
{
    for(int x = 0; x < 3; x++) 
       text[x] = textBox1.Lines[x];
}

...而 TextBox.Lines 是一个 string[],因此它是原始帖子中 text1 变量的完全替代品。 - Polyfun
我想要对 [1] [2] [3] 字符串进行循环,我该怎么做? - Manar Al Saleh
2
注意:Textbox.lines仅适用于Windows Forms(不适用于Webforms) - Douglas Timms

10

在C#中,简单的编程方法可以从多行文本框中逐行读取和写入。

逐行写入:

注:保留原文html标签。

textbox1.AppendText("11111111+");
textbox1.AppendText("\r\n222222222");
textbox1.AppendText("\r\n333333333");
textbox1.AppendText("\r\n444444444");
textbox1.AppendText("\r\n555555555");

逐行阅读:

for (int i = 0; i < textbox1.Lines.Length; i++)
{
    textbox2.Text += textbox1.Lines[i] + "\r\n";
}

1
您可以使用以下代码片段从多行文本框中读取逗号分隔和换行符分隔的值 -
 if (!string.IsNullOrEmpty(Convert.ToString(txtBoxId.Text)))
        {
            string IdOrder = Convert.ToString(txtBoxId.Text.Trim());

            //replacing "enter" i.e. "\n" by ","
            string temp = IdOrder.Replace("\r\n", ",");            

            string[] ArrIdOrders = Regex.Split(temp, ",");

            for (int i = 0; i < ArrIdOrders.Length; i++)
            {
              //your code
            }
         }

我希望这会对你有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接