xoxo_tw
xoxo_tw

Reputation: 269

C# Loadl List into textbox WinForms

I have a problem when I try to display the list into the textbox. It only displays the last line from the list.txt file. I think for each new line it overwrites the first line from the textbox all the time ? thus showing only the last line from the file ?

what is it I need to think of to get it right ?

private void Form1_Load(object sender, EventArgs e)
        {

            const string f = "list.txt";

            List<string> myList = new List<string>();

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    myList.Add(line);
                }
            }


            foreach (string s in myList)
            {

                textBox1.Text = string.Join(Environment.NewLine, s);

            }


        }

Upvotes: 3

Views: 8980

Answers (3)

MethodMan
MethodMan

Reputation: 18863

Based on my comment you can do this in one simple line by eliminating the foreach loop

textBox1.Text = string.Join(Environment.NewLine, myList.ToArray());

or just use the myList works the same

textBox1.Text = string.Join(Environment.NewLine, myList);

Upvotes: 0

Behrad Farsi
Behrad Farsi

Reputation: 1110

Instead of this:

foreach (string s in myList) { textBox1.Text = string.Join(Environment.NewLine, s); }

Try:

textBox1.Text = string.Join(Environment.NewLine, myList);

And also make sure multiline property of textbox1 is set to true.

Upvotes: 5

Dan Hunex
Dan Hunex

Reputation: 5318

Because every time, you assign directly to the Text property which will remove the previous one . Here is the fix . Make Multiline of textbox true.

private void Form1_Load(object sender, EventArgs e)
        {

            const string f = "list.txt";

            List<string> myList = new List<string>();

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    myList.Add(line);
                }
            }

            var listString = new StringBuilder()
            foreach (string s in myList)
            {
                listString.Append(Environment.Newline)
                listString.Append(s);              

            }
             textBox1.Text = listString.ToString();

        }

Upvotes: 0

Related Questions