【问题标题】:C# listView check for repeated "fileName" entriesC# listView 检查重复的“文件名”条目
【发布时间】:2010-08-31 18:24:27
【问题描述】:

我是 C# 新手

我只是想问在我执行ADD() 方法之前是否可以检查列表视图中的 SUBItem 是否有重复值??

假设我有一个列表视图,我可以添加/删除项目

我可以有很多项目和子项目

我想在将要打开的文件添加到列表视图之前进行检查

我要放入的文件是文件名,例如example.txt

如果子项中存在这个文件,我不会添加到列表视图中

有人知道如何根据我要添加的值检查子项值吗?

TIA

【问题讨论】:

    标签: c# listview subitem


    【解决方案1】:

    好吧,您可以遍历ListViewItems 属性,然后是每个项目的Subitems 属性,最后检查子项目的Text 属性。

    另一种选择是将已添加的项目存储在列表中,并检查它是否已包含您要添加的项目。

    编辑:根据要求,在下面添加示例代码。

    private bool _CheckFileName(string fileName)
    {
        foreach(ListViewItem item in this.myListView.Items)
        {
            // this is the code when all your subitems are file names - if an item contains only one subitem which is a filename,
            // then you can just against that subitem, which is better in terms of performance
            foreach(ListViewItem.ListViewSubItem subItem in item.SubItems)
            {
                // you might want to ignore the letter case
                if(String.Equals(fileName, subItem.Text))
                {
                    return false;
                }
            }
        }
    
        return true;
    }
    
    using(var ofd = new OpenFileDialog())
    {
        // ... setup the dialog ...
    
        if(ofd.ShowDialog() == DialogResult.Cancel)
        {
            // cancel
            return;
        }
    
        // note that FileOpenDialog.FileName will give you the absolute path of the file; if you want only the file name, you should use Path.GetFileName()
        if(!_CheckFileName(ofd.FileName))
        {
            // file already added
            return;
        }
    
        // we're cool...
    }
    

    我没有测试代码,所以我可能有一些拼写错误,如果是这样,请添加评论,我会修复它(但如果你先尝试自己弄清楚可能会更好: ))。

    【讨论】:

    • 这当然是最简单的选择,但它是一个 O(n^2) 解决方案,在大型数据集上运行不佳。
    • 嗨!感谢您的指导...但我想知道如何完成编码部分...如检查部分,请帮助foreach (listViewItem item in listView1.Items),它将遍历 ListView 的 Items 属性{ 如何检查 listview在添加到列表视图之前使用 openfiledialog 时的子项? }
    【解决方案2】:

    您可以创建一个帮助类,其中包含有关每个项目的信息。为每个ListViewItem 创建一个新的此类实例并将ListViewItem.Tag 设置为此实例。

    您只需遍历所有项目,获取项目的帮助对象并与该帮助对象进行比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2012-01-05
      • 2013-12-01
      • 1970-01-01
      • 2013-11-30
      • 2012-05-09
      相关资源
      最近更新 更多