C # listview in winforms not displaying added items

I am trying to select a directory from an open file dialog in C #, but when I actually add items to the list view, it does not appear. This is my code so far ... am I missing something?

private void btnChoose_Click(object sender, EventArgs e) { try { FolderBrowserDialog folderPicker = new FolderBrowserDialog(); listLeft.View = View.Details; if (folderPicker.ShowDialog() == DialogResult.OK) { DirectoryInfo di = new DirectoryInfo(folderPicker.SelectedPath); FileInfo[] files = di.GetFiles(); DirectoryInfo[] directories = di.GetDirectories(); foreach (DirectoryInfo directory in directories) { listLeft.Items.Add("Directory " + directory.Name); } foreach (FileInfo file in files) { listLeft.Items.Add(file.Name); } } } catch (Exception ex) { MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 

EDIT: Added this screenshot with descriptions ... enter image description here

+4
source share
3 answers

I assume listLeft is your ListView. You need to add the following subtypes:

  foreach (DirectoryInfo directory in directories) { ListViewItem lvi = new ListViewItem(); lvi.SubItems.Add("Directory " + directory.Name); listLeft.Items.Add(lvi); } foreach (FileInfo file in files) { ListViewItem lvi = new ListViewItem(); lvi.SubItems.Add(file.Name); listLeft.Items.Add(lvi); } 

EDIT: Try the following:

 private void button1_Click(object sender, EventArgs e) { try { listLeft.Columns.Add(new ColumnHeader()); FolderBrowserDialog folderPicker = new FolderBrowserDialog(); listLeft.View = View.Details; if (folderPicker.ShowDialog() == DialogResult.OK) { DirectoryInfo di = new DirectoryInfo(folderPicker.SelectedPath); FileInfo[] files = di.GetFiles(); DirectoryInfo[] directories = di.GetDirectories(); foreach (DirectoryInfo directory in directories) { listLeft.Items.Add("Directory " + directory.Name); } foreach (FileInfo file in files) { listLeft.Items.Add(file.Name); } } } catch (Exception ex) { MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 
+4
source

It should be added to the list - if there are objects in directories and objects ... try setting a breakpoint in each method and see what happens. If breakpoints don't start, then something is wrong with your Get () methods ...

0
source

your question indicates "listview in winforms".

But System.Windows.Forms.ListBox doesn't have a View property, so your line of code

 listLeft.View = View.Details; 

Doesn't compile when I try to play.

Perhaps you are possibly referencing a WPF list? In this case, can you show us more code, in particular data binding?

-4
source

Source: https://habr.com/ru/post/1502240/


All Articles