0

我是 C# 新手

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

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

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

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

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

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

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

TIA

4

2 回答 2

1

好吧,您可以遍历ListView的Items属性,然后是每个项的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...
}

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

于 2010-08-30T10:57:27.187 回答
0

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

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

于 2010-08-30T11:11:56.493 回答