简体   繁体   English

如何使用字符串数组并逐行显示

[英]How to use the array of strings and display it line by line

How can I display what has been added to my list and show it in the textbox line by line? 如何显示已添加到列表中的内容,并逐行显示在文本框中? I am adding data from a text file into a list so that I can append text after every line. 我正在将文本文件中的数据添加到列表中,以便可以在每行之后添加文本。

    private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            var list = new List<string>();

            using (var sr = new StreamReader("C:\\File1.txt"))
            {
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    list.Add(line);
                }

            }

            TextBox.Text = string.Join(Environment.NewLine, list.ToArray());

        }
        catch (Exception ex)
        {
            MessageBox.Show("An error has occurred" + ex.Message);
        }


    } 

Something like: 就像是:

aTextbox.Text = string.Join(Environment.NewLine, list.ToArray());

This will take every string in your array and add a newline between them. 这将获取数组中的每个字符串,并在它们之间添加换行符。

If you only need to show file source inside a TextBox there is no need to save the data inside a List<string> first. 如果只需要在TextBox显示文件源,则无需先将数据保存在List<string> Just do: 做就是了:

string text = "";
using (var sr = new StreamReader("C:\\File1.txt"))
{
     string line;
     while ((line = sr.ReadLine()) != null)
     {
          text += line + Environment.NewLine;
     }
}
aTextbox.Text = text;

Another way - without looping through all the lines in the file. 另一种方法-无需循环遍历文件中的所有行。

using System.IO;

private void WriteFileContentsToTextBox(string filePath)
{
     // Always check for existence of the file
     if (File.Exists(filePath))
     {
        // Open the file to read from. 
        string[] readText = File.ReadAllLines(filePath, Encoding.UTF8);
        myMultilineTextBox.Text = string.Join(Environment.Newline, readText);
     }
 }     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM