0

I want to make a listview of files in folder,but it doesn't work. What's wrong with this code?

DialogResult wczytywanie_z_folderu = new DialogResult();
wczytywanie_z_folderu = folderBrowserDialog1.ShowDialog();
string[] pliki_w_folderze = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
if (wczytywanie_z_folderu == DialogResult.OK)
{
    List<string> lista = new List<string>();
    lista = pliki_w_folderze.ToList();

    int dl_listy = lista.Count;
    int dlugosc = pliki_w_folderze.Length;

    for (int i = 0; i == dlugosc; i = i + 1)
    {
        string alfabet = "abcdefghijklmnopqrstuwvxyz";
        char[] litery = alfabet.ToCharArray();
        Random r = new Random();
        string temp = "";
        for (int j = 0; j < 1; j++)
        {
            int random_letter = r.Next(litery.Length);
            temp += litery[random_letter].ToString();

            ListViewItem str = new ListViewItem(temp);

            str.Text = lista[i];
            listView1.Items.Add(str);
        }
}
1
  • Unrelated to your question: The first line (DialogResult wczytywanie_z_folderu = new DialogResult();) is redundant. Remove it and just write DialogResult wczytywanie_z_folderu = folderBrowserDialog1.ShowDialog();. The same applies to the new List<string>, it’s also redundant. Commented Sep 6, 2010 at 0:14

1 Answer 1

3

Your for should be:

for (int i = 0; i < dlugosc; i = i + 1)

Better yet, use foreach!

It's not clear why you're going through all the random numbers to get an alphabet char, only to simply overwrite the Text property with the name of the file.

Try this instead, to help make life easier.

if (wczytywanie_z_folderu == DialogResult.OK)
{ 
    listview1.Items.AddRange( pliki_w_folderze
                                  .Select(f => new ListViewItem(f))
                                  .ToArray());
}
Sign up to request clarification or add additional context in comments.

1 Comment

@luc: glad it helped. consider marking answers that helped you out the most to your questions as 'accepted answers' It's the green checkmark. It helps you to get better answers to your questions in the end!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.