Search code examples
c#listviewitem

How to add an item in specific column in listViewItem


I have list all item using foreach by its filename. Now, how can I add in the second column the path of each files listed in the first column? I have already add a column or collection on the properties.

    foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
    {
        string fileName = Path.GetFileName(filePath);
        listViewFiles.Items.Add(fileName);
    }

Solution

  • Try this:

    // Set up List View
    listViewFiles.View = View.Details;
    listViewFiles.Columns.Clear();
    listViewFiles.Columns.Add("File name");
    listViewFiles.Columns.Add("File path");
    
    // Populate with files and file paths
    foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
    {
        string fileName = Path.GetFileName(filePath);
        listView1.Items.Add(fileName).SubItems.Add(new FileInfo(fileName).DirectoryName);
    }
    

    EDIT:

    Personally, I find it easier to instantiate a DirectoryInfo for this kind of thing, it populate lots of useful fields for you. So you could do:

    DirectoryInfo di = new DirectoryInfo(path);
    foreach (FileInfo fi in di.GetFiles(fileType, SearchOption.AllDirectories))
        listViewFiles.Items.Add(fi.Name).SubItems.Add(fi.DirectoryName);