将文本文件读入列表视图的问题c#

问题描述:

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

在文件中的文本

ABC *高清* 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(); 


    } 
+0

您可以使用LINQ –

+1

也许在while循环之前调用'listView1.Items.Clear();'? –

当你两次点击此按钮,以下行重复两次:

listView1.Items.Add(lv); 

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

只需在添加项目之前清除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(); 


}