Search code examples
c#listviewsubitem

C# listView check for repeated "fileName" entries


I am new to C#

I just want to ask if is it possible to check against a SUBItem in a listview for repeated values before i do a ADD() method??

Lets say i have a listview and i can add/delete items

I can have numerous items and subitems

I would like to perform a check before adding the file that i'm opening into the listview

The file that I'm going to put into would be, name of a file, eg example.txt

And if this file exists in the subitem, i will not add into the listview

Does anyone have any idea on how to check a subitem value against the value that I'm going to add into?

TIA


Solution

  • Well, you can iterate through the Items property of the ListView, and then the Subitems property for each item and finally check against the subitem's Text property.

    The other option is to store the already added items in a List, and check if it already contains that item you want to add.

    Edit: as requested, added sample code below.

    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...
    }
    

    I didn't test the code so it is possible that I have some typos, if so, please add a comment and I'll fix it (though perhaps it would be better if you tried to figure it out yourself first :)).