2015-11-03 60 views
0

我正在嘗試逐行讀取文本文件並使用分隔符分割文本並將其插入列表視圖中的三列中。每次我點擊一個按鈕,閱讀功能必須執行。但是當我點擊按鈕兩次時,我得到了重複的值。我如何解決這個問題?我在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();'? –

回答

0

當你兩次點擊此按鈕,以下行重複兩次:

listView1.Items.Add(lv); 

要麼你需要重新創建對象listView1在你的函數開始或者你需要在開始時清除它。

0

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


}