2013-07-20 42 views
0

我有第二列如何刪除列表視圖第二列中列出的選定文件?

列出的文件的一些路徑的ListView和我想刪除當然 我也想刪除的項目在第二列中列出的所有選定的文件。

我試了一下

For Each i As ListViewItem In ListView1.SelectedItems 
    ListView1.Items.Remove(i) 
    System.IO.File.Delete(i) 
Next 

而且它刪除選定的項目,但不刪除在第二列中選擇文件.. ,因爲我得到了一個錯誤類型System.Windows.Forms的的

值.Listviewitem不能轉換爲字符串

回答

1

循環變量的類型iListViewItemFile.Delete()接受string類型的文件路徑,則需要糾正該問題。爲了從第二列的文件路徑使用ListViewItem'sSubItems屬性:

Dim idx As Integer = ListView1.SelectedItems.Count - 1 
For i As Integer = idx To 0 Step -1 
    Dim lvi As ListViewItem = ListView1.SelectedItems(i) 
    System.IO.File.Delete(lvi.SubItems(1).Text) 
    ListView1.Items.Remove(lvi) 
Next 
+0

ArgumentOutOFRangeException未處理 | InvalidArgument = 1的值不適用於索引 |參數名稱:索引 – 28121327

+0

確保_ListView1_包含至少2列?這個例外來自哪條線? – Coder

+0

Line:System.IO.File.Delete(lvi.SubItems(1).ToString()) – 28121327

1
  • listviewItem得到一個值,你需要訪問ListviewItem.Subitems財產。你想要的值在第二列,所以它是subitems(1)

  • 你不能循環到選定的項目,並像這樣刪除循環中的項目。選定的項目集合將會更改,您將得到一個例外。

  • 我建議您在Try Catch塊中刪除文件。如果您有異常,請勿刪除ListviewItem。


這應該工作。

If ListView1.SelectedItems.Count > 0 
    For i As Integer = ListView1.SelectedItems.Count - 1 To 0 Step -1 
     Dim lvi As listviewItem = ListView1.SelectedItems(0) 
     Try 
     Dim filepath as String = lvi.subitems(1).Text 
     If System.IO.File.Exists(filepath) Then 
      System.IO.File.Delete(filepath) 
      ListView1.Items.Remove(lvi) 
      End If 
     Catch ex as Exception 
     ' Do something 

     'you will have another exception for the next item because 
     'It will try to delete the same (selectedItem(0)) 
     'So exit 
      Exit for 
     End Try 
    Next 
End If 
+0

不起作用,錯誤在這一行:System.IO.File.Delete(lvi.subitem(1) | subitem不是System.Windows.Forms.ListViewItem和')'的成員 | 我添加了一個「)」,然後只有'子項目不是System.Windows.Forms.ListViewItem的成員' – 28121327

+0

@ 28121327你是正確的,我的示例代碼中有錯誤的部分。更新後的答案有幫助嗎? – Chris

相關問題