我编写了这段代码来从C#中的文本文件中读取和写入数据,但它不起作用

时间:2015-06-19 01:34:12

标签: c# winforms input output add

我写了这段代码来读取和写入文本文件中的数据并显示我得到的错误是在第49,50和51行。错误是:

  

错误1'System.Windows.Forms.TextBox'不包含'Items'的定义,也没有扩展方法'Items'接受类型'System.Windows.Forms.TextBox'的第一个参数'(是你错过了使用指令或程序集引用?)C:\ Users \ aric \ documents \ visual studio 2013 \ Projects \ WeekSeven \ WeekSeven \ Form1.cs 49 25 WeekSeven

我无法弄清楚为什么它不接受我的代码并抛出此错误,请帮助我不知道如果您有任何问题我可以添加其他详细信息,我会回复您在几分钟内。

       //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 个答案:

答案 0 :(得分:0)

尝试更改以下代码:

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

为:

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

根据您的要求更改添加的文字