Search code examples
c#streamreaderstreamwriter

Stream Reader (Pull data from .txt file to be displayed in listBox)


I have a .txt file that, in the form2, I am writing to. I now need to call up the .txt file and then display each line of characters into a listBox on form3. But I am getting errors.

Error1: 'string' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

Error2: Cannot convert method group 'ReadLine' to non-delegate type 'string'. Did you intend to invoke the method?

Side Note the file is named "data.txt" and form 3 is named "Stats".

public partial class Stats : Form
{
    public Stats()
    {
        InitializeComponent();
    }

    private void Stats_Load(object sender, EventArgs e)
    {
        StreamReader StreamIn = File.OpenText(@"data.txt");
        string Record = StreamIn.ReadLine();

        while (Record != null)
        {
            listBox1.Text.Add(Record);
            Record = StreamIn.ReadLine;
        }
        StreamIn.Close();
    }
}

Solution

  • listBox1.Text is of type string. String does not have an Add function. The property Text represents the selected item, not the collection of items. You can add items to the Items property", like this:

    listBox1.Items.Add(Record);
    

    Second, all methods must end with ( zero or more parameters and ):

    Record = StreamIn.ReadLine();
    

    You do it correctly in the line of code where you read a record.

    * EDIT (after comments of Dmitry Bychenko) *

    Another way to do it faster is:

    private void Stats_Load(object sender, EventArgs e)
    {
        listBox1.Items.AddRange(File.ReadAllLines(@"data.txt"));
    }