Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to list the files in the folder in listview

I tried this code
DirectoryInfo di = new DirectoryInfo(@"C:\Users\Yusuf\Desktop\excel");
Dosyalar = di.GetFiles("*.csv");

ListViewItem item = new ListViewItem();

foreach (FileInfo file in Dosyalar)
{
    for (int i = 1; i < Dosyalar.Length; i++)
    {
        item.SubItems.Add(file.Name);
        item.Text = i.ToString();
        listView2.Items.Add(item);
    }
}

I'm getting result like this

1 mytest.csv
2 mytest.csv
3 mytest.csv
1 mytest1.csv
2 mytest1.csv
3 mytest1.csv
1 mytest2.csv
2 mytest2.csv
3 mytest2.csv


I want to get result like this

1 mytest.csv
2 mytest1.csv
3 mytest2.csv


What I have tried:

foreach (FileInfo file in Dosyalar)
{
    ListViewItem item = new ListViewItem();
    for (int i = 1; i < Dosyalar.Length; i++)
    {
        item.SubItems.Add(file.Name);
        item.Text = i.ToString();
        listView2.Items.Add(item);
    }
}


ListViewItem item = new ListViewItem();
foreach (FileInfo file in Dosyalar)
    {
        item.SubItems.Add(file.Name);
    }

for (int i = 1; i < Dosyalar.Length; i++)
    {
        
        item.Text = i.ToString();
        
    }
        listView2.Items.Add(item);
Posted
Updated 17-May-22 11:24am

I can see two immediate problems with your code:

  1. You're looping over the file array twice
  2. You're not creating a new ListViewItem each time you add it to the list

C#
foreach (FileInfo file in Dosyalar) // <-- looping over the 3 items here
{
    ListViewItem item = new ListViewItem();
    for (int i = 1; i < Dosyalar.Length; i++) // <-- looping over the 3 items again here
    {

You don't even need to reference Dosyalar.Length, you can instead just use an index variable to track the current item:
C#
int index = 1;

foreach (FileInfo file in Dosyalar)
{
  ListViewItem item = new ListViewItem();
  item.Text = index.ToString();
  item.SubItems.Add(file.Name);
  listView2.Items.Add(item);

  index++;
}
 
Share this answer
 
You need to create a new item each time round the loop when you add it - otherwise, you just overwrite the single existing instance and that won't work, as you have seen...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900