【问题标题】:Issues in reading text file into list view c#将文本文件读入列表视图 C# 的问题
【发布时间】:2016-02-03 04:03:15
【问题描述】:

我正在尝试逐行读取文本文件并使用分隔符,拆分文本并将其插入到列表视图中的三列中。每次单击按钮时,都必须执行读取功能。但是当我点击按钮两次时,我得到了重复的值。我该如何解决?我是c#初学者

文件中的文本

abc*def*ghi

jkl*mno*pqr

列表视图中的输出

abc|def|ghi

jkl|mno|pqr

abc|def|ghi

jkl|mno|pqr

  public void read(string destinination)
    {
        Form1 f1 = new Form1();
        StreamReader sw = File.OpenText(destinination);
        string s = "";

        try
        {
            while ((s = sw.ReadLine()) != null)
            {
                string[] words = s.Split('*');
                ListViewItem lv = new ListViewItem(words[0].ToString());
                lv.SubItems.Add(words[1].ToString());
                lv.SubItems.Add(words[2].ToString());
                listView1.Items.Add(lv);
            }
        }
        catch ( Exception ex)
        {
            Console.WriteLine(ex);
        }

        sw.Close();


    }

【问题讨论】:

  • 可能在 while 循环之前调用 listView1.Items.Clear();

标签: c# .net


【解决方案1】:

当您两次单击按钮时,以下行重复两次:

 listView1.Items.Add(lv);

您需要在函数开始时重新创建对象 listView1,或者需要在开始时清除它。

【讨论】:

    【解决方案2】:

    在添加项目之前,只需清空ListView,这样下次点击按钮时,已经添加的项目就会被清空。

    public void read(string destinination)
    {
        Form1 f1 = new Form1();
        StreamReader sw = File.OpenText(destinination);
        string s = "";
        ListView1.Item.Clear();
        try
        {
            while ((s = sw.ReadLine()) != null)
            {
                string[] words = s.Split('*');
                ListViewItem lv = new ListViewItem(words[0].ToString());
                lv.SubItems.Add(words[1].ToString());
                lv.SubItems.Add(words[2].ToString());
                listView1.Items.Add(lv);
            }
        }
        catch ( Exception ex)
        {
            Console.WriteLine(ex);
        }
    
        sw.Close();
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多