【问题标题】:I wrote this code to read and write data from a text file in C# but it's not working我编写了这段代码来从 C# 中的文本文件中读取和写入数据,但它不起作用
【发布时间】:2015-06-19 01:34:11
【问题描述】:

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

错误 1“System.Windows.Forms.TextBox”不包含“Items”的定义,并且找不到接受“System.Windows.Forms.TextBox”类型的第一个参数的扩展方法“Items”(是您缺少 using 指令或程序集引用?) 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();

【问题讨论】:

  • 得读懂你的错误。 contactTextBoxTextBox 没有项目,它只有一个文本字符串。你想用contact做什么?
  • 使用ListBox 控件而不是TextBox,因为texbox 控件只能包含一项。或任何其他可以包含列表的控件,例如DropDownList。情节转折:这看起来像一个任务:)

标签: c# winforms input output add


【解决方案1】:

尝试更改以下代码:

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 += "";
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2020-06-26
    • 2011-03-08
    • 2012-06-23
    • 2018-01-12
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多