Question Multiline label not working

Nichan-san

Member
Joined
Jan 6, 2020
Messages
6
Programming Experience
Beginner
Hello, beginner coder here. I'm creating a program that reads a text file and outputs its text to a label.

Problem:

The program reads the file. However, only the last line appears.
Assuming the label is unchanged, how can I fix my code so it outputs the rest of the text?

FILE: /<project name>/bin/Debug


C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;

namespace Code_Test
{
    public partial class Home : Form
    {
        public Home()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            //used to display each line from file
            string Line;

            try
            {

                //create new file, if applicable
                StreamWriter sw = new StreamWriter("Text1.txt");

                sw.WriteLine("If this text successfully overrides the label");
                sw.WriteLine("you will see this text.");

                sw.Close();

                //END EDIT

                //reads a specified file (Text1.txt)
                StreamReader sr = new StreamReader("Text1.txt");
                Line = sr.ReadLine();

                while (Line != null)
                {

                    //text to output window (debug; see below)
                    Console.WriteLine(Line);

                    //converts label to text
                    LblText.Text = Line;
                    Line = sr.ReadLine();
                }

                sr.Close();
            }

            //catch errors                                           
            catch (Exception r)                                                                                                                                                                           
            {                                                                     

                Console.WriteLine("Exception: " + r.Message);
            }

            //end file
            finally
            {

                Console.WriteLine("End of file");
            }
        }
    }
}
 
Last edited:
C#:
LblText.Text = System.IO.File.ReadAllText("Text1.txt");
 
And don't just read one line sr.ReadLine();

Also don't use a stream reader/writer. JohnH's suggestion is much more lightweight.
C#:
            System.IO.File.ReadAllText("Text1.txt");
            System.IO.File.WriteAllText("Text1.txt", "foo");
 
Back
Top Bottom