2017-02-18 128 views
0

在C#窗口应用程序中,我比较两个不同的字符串数组,并根据哪个数组大小很大,我将项目添加或删除到列表视图框。使用下面的代码,我可以添加到列表视图没有任何问题,但我无法从中删除。无法从lsitviewbox中删除项目

我得到一个错误,说。

“错误CS1503,参数1:无法从 '字符串' 转换 'System.Windows.Forms.ListViewItem'”

这里是从我的代码的摘录

 string[] currentFilesList = GetFileList(); 
     if (currentFilesList.Length > prevFilesList.Length) 
     { 
      var addedList = currentFilesList.Except(prevFilesList).ToArray(); 
      foreach (var item in addedList) 
      { 
       listView1.Items.Add(item); 
      } 
     } 
     if (currentFilesList.Length < prevFilesList.Length) 
     { 
      var removedList = prevFilesList.Except(currentFilesList).ToArray(); 
      foreach (string item in removedList) 
      {     
        listView1.Items.Remove(item); //I get error here on "item" Argument 1: cannot convert from 'string' to 'System.Windows.Forms.ListViewItem'"      
      } 
     } 
     prevFilesList = currentFilesList; 

我尝试了字符串和var,但结果相同。

回答

0

您可以通过

foreach (string item in removedList) 
{ 
     var toRemove =listView1.Items.Find(item); 
     if (toRemove != null) 
     { 
      listView1.Items.Remove(toRemove); 
     } 
} 

删除的项目,或者您可以使用RemoveByKey

foreach (string item in removedList) 
    { 

       listView1.Items.RemoveByKey(item); 

    } 
0

您可以通过使用LINQ

var newlist = listView1.Cast<ListViewItem>().Where(p=>p.Text.Contains("OBJECT")).ToList().ForEach(listBox1.Items.Remove); 
试试这个