Havel The Gravel
Havel The Gravel

Reputation: 21

Having trouble with adding lines to a rich text box from a list

    private void btnAdd_Click(object sender, EventArgs e)
    {
        StreamWriter outputFile;
        outputFile = File.AppendText("texter.txt");
        outputFile.WriteLine(txtInput.Text);
        outputFile.Close();

        List<String> mainList = new List<String>();

        StreamReader inputFile;
        inputFile = File.OpenText("texter.txt");
        while (inputFile.EndOfStream == false)
        {
            mainList.Add(inputFile.ReadLine());
        }
        inputFile.Close();

        for (int i = 0; i < mainList.Count; i++)
        {
            txtOutput.Text = mainList[i];
        }
    }

This is inside a button handler, and there is also a text box for input involved. Whenever I hit the button, however, it overwrites the previous entry. I want to get everything from my list into the text box.

Upvotes: 0

Views: 55

Answers (2)

Valentin
Valentin

Reputation: 5488

You are using = operator which doesn't add anything, it assigns value to a property. Use += operator or assign the text value to a sum of a previous value + new value.

txtOutput.Text += mainList[i];
// or 
txtOutput.Text = txtOutput.Text +  mainList[i];
// or 
txtOutput.Text = mainList[i] + txtOutput.Text;

But I suggest to use String.Format instead of + or += operator

txtOutput.Text = string.Format("{0}\n{1}", mainList[i], txtOutput.Text);

Also, you can avoid for-loop using Aggregate or Join instead.

var text = mainList.Aggregate((x, next) => string.Format("{0}\n{1}", next, x));
var text = string.Join("\n", mainList);

Also, you can read entire file in one go string using the ReadAllText method.

var text = File.ReadAllText("texter.txt");

Then add it to the TextBox

 txtOutput.Text = string.Format("{0}\n{1}", mainList[i], text);

Upvotes: 2

Kalten
Kalten

Reputation: 4312

3 options :

Fix assignment

txtOutput.Text += mainList[i] + Environment.NewLine;

Or replace for loop

txtOutput.Text = string.Join(Environment.NewLine, mainList);

Or replace loop and StreamReader

txtOutput.Text = File.ReadAllText("texter.txt");

Upvotes: 0

Related Questions