I wrote this code to read and write data from a text file in C# but it's not working

172 Views Asked by At

I wrote this code to read and write data from a text file and display it the errors I get are on lines 49,50 and 51. The error is:

Error 1 'System.Windows.Forms.TextBox' does not contain a definition for 'Items' and no extension method 'Items' accepting a first argument of type 'System.Windows.Forms.TextBox' could be found (are you missing a using directive or an assembly reference?) C:\Users\aric\documents\visual studio 2013\Projects\WeekSeven\WeekSeven\Form1.cs 49 25 WeekSeven

I can't figure out why it's not accepting my code and throwing this error, please help I don't know what other details I can add at the moment if you have any questions ask and I'll get back to you within a couple of minutes.

       //Text writer to write data to text
        //StreamWriter("data.txt", true) here true represents to append data
        TextWriter write = new StreamWriter("data.txt", true);
        //write data to the file
        write.WriteLine(Nameadd.Text);
        write.WriteLine(Mailadd.Text);
        write.Close();//closing file
        //open file for reading
        TextReader reader = new StreamReader("data.txt");
        string str;
        //reading all lines of data from file
        //adding to list box
        contact.Clear();
        while ((str = reader.ReadLine()) != null)
        {
            contact.Items.Add(str);
            contact.Items.Add(reader.ReadLine());
            contact.Items.Add("");
        }

        reader.Close();//closing file
        //clearing text boxes
        Nameadd.Clear();
        Mailadd.Clear();
1

There are 1 best solutions below

0
On

Try changing the following code:

while ((str = reader.ReadLine()) != null)
{
    contact.Items.Add(str);
    contact.Items.Add(reader.ReadLine());
    contact.Items.Add("");
}

to:

while ((str = reader.ReadLine()) != null)
{
    contact.Text += str;
    contact.Text += reader.ReadLine();
    contact.Text += "";
}

Change the added text as per your requirements