'UWP C# Select Multiple items and display name as single items on Listview

Hello all hope you all are having an awesome week;

enter image description hereI'm pretty new to UWP and was trying to create a very simple app, first I wanted to be able to select any file or files and list the names on a listview, I am very close, but as a normal foreach loop it is adding the items properly but adding up the names please see the results and my code below.

Mainpage.xaml
 <Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">
            <ListView x:Name="ListViewtouse" >
               
            </ListView>
               
        </Grid>
MainPage.xaml.cs
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add("*");
            IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
            if (files.Count > 0)
            {
                StringBuilder output = new StringBuilder();
                // The StorageFiles have read/write access to the picked files.
                // See the FileAccess sample for code that uses a StorageFile to read and write.
                foreach (StorageFile file in files)
                {
                    output.Append(file.Name + "\n");
                    ListViewtouse.Items.Add(output.ToString());
                }
            }
            else
            {
                Console.WriteLine("Operation cancelled.");
            }

RESULTS: file1 <<--- ListView Item 1

file1 file2 <<--- Listview Item 2

file1 file2 <<--- Listview Item 3 file3

To me this does makes sense but is there a way to have only 1 name per listview item instead of adding them up? I attached an image for further reference.

Thanks in advance.



Solution 1:[1]

The reason for this behavior is that you are using a StringBuilder object for all the loops without resetting the StringBuilder object. The StringBuilder object will contain the last item's name when you add a new item name to it.

You could move that line of code into the foreach loop.

Like this:

           foreach (StorageFile file in files)
            {
                StringBuilder output = new StringBuilder();
                output.Append(file.Name + "\n");
                ListViewtouse.Items.Add(output.ToString());
            }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roy Li - MSFT