列出<string>到listbox.Items C#

时间:2017-08-03 20:40:03

标签: c#

我有这段代码

public List<string> GetAllFilesFromFolder(string root, bool searchSubfolders)
{
    Queue<string> folders = new Queue<string>();
    List<string> files = new List<string>();
    folders.Enqueue(root);
    while (folders.Count != 0)
    {
        string currentFolder = folders.Dequeue();
        try
        {
            string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
            files.AddRange(filesInCurrent);
        }
        catch
        {
            // Do Nothing
        }
        try
        {
            if (searchSubfolders)
            {
                string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
                foreach (string _current in foldersInCurrent)
                {
                    folders.Enqueue(_current);
                }
            }
        }
        catch
        {
            // Do Nothing
        }
    }
    return files;
}

列出特定目录中的所有文件,并搜索忽略List<string>

的例外情况的子目录

但是如何将List<string>结果列入列表框?

我试图把

foreach (var foo in files)
{
    listbox1.Items.Add(foo);
}

return files;之后但由于某种原因在列表框中没有显示...我使用的是基本的Windows窗体

1 个答案:

答案 0 :(得分:4)

尝试

listBox1.DataSource = MyList;

(重复:C#: easiest way to populate a ListBox from a List