【问题标题】:My program is duplicating the input stream from a textbox C#我的程序正在从文本框 C# 复制输入流
【发布时间】:2017-02-18 05:16:57
【问题描述】:

所以,我是 C# 的新手,我的程序中有这个列表框,它复制了从文本框中读取的内容。 每当我启动我的程序时,它会将 save.txt 文件的内容加载到列表框中,但是当它这样做时,它会加载所有 save.txt 内容的副本。我尝试在加载内容之前清除列表框,但它不起作用。

这是我的代码:

    private void readList()
    {
        string line;
        listBox.Items.Clear(); //I tried to clear the listbox but it's not working
        listBox.Items.AddRange(File.ReadAllLines(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
        using (StreamReader sr = new StreamReader("save.txt"))
            while ((line = sr.ReadLine()) != null)
            {
                listBox.Items.Add(line);
            }
    }

    public myAgenda()
    { 
        InitializeComponent();
        readList(); 
    }

    private void add_btn_Click(object sender, EventArgs e)
    {

        if (string.IsNullOrWhiteSpace(add_txt.Text))
        {
            MessageBox.Show("Error: Please enter a value");
        }
        else
        {
            holder = add_txt.Text;
            listBox.Items.Add(ctr + " " + holder);
            ctr++;
            add_txt.Text = " ";
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        const string sPath = "save.txt";
        System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
        foreach (var item in listBox.Items)
        {
            SaveFile.WriteLine(item);
        }
        SaveFile.Close();
        Application.Exit();
    }

【问题讨论】:

  • 是再次复制整个流还是复制刚刚填充的 save.txt 中的条目?

标签: c# winforms listbox


【解决方案1】:

您在readlist 方法中填写listbox 两次,即

第一次:

  listBox.Items.AddRange(File.ReadAllLines(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));

第二次:

        using (StreamReader sr = new StreamReader("save.txt"))
        while ((line = sr.ReadLine()) != null)
        {
            listBox.Items.Add(line);
        }

您可以删除其中一种方法来填充内容。第一种方法更便于阅读。

【讨论】:

    【解决方案2】:

    您在 listBox 上复制了两次内容。

    尝试这样做:

    private void readList()
    {
        string line;
        listBox.Items.Clear(); 
    
        //Comment out this line then put the File Directory on the StreamReader
        //listBox.Items.AddRange(File.ReadAllLines(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
    
        using (StreamReader sr = new StreamReader(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"))
            while ((line = sr.ReadLine()) != null)
            {
                listBox.Items.Add(line);
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 2016-08-11
      • 2010-11-10
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      相关资源
      最近更新 更多