3

I have List of objects of class Book:

 public static List<Book> ListBooks = new List<Book>() {
            new Book(1, "Title", "Author", 2004)            };

Now, I want to insert this list to ListView in Window Form. In WPF it's easy, but in Windows Forms "DataSource" does not work.

I added some columns, but how can I bind this list to listview?

thesecretmaster
  • 1,950
  • 1
  • 27
  • 39
nvent
  • 81
  • 1
  • 8
  • 1
    You may consider using readonly `DataGridView` instead. – Ivan Stoev Jun 04 '16 at 11:54
  • I must use ListView. This is the requirement for the task. – nvent Jun 04 '16 at 11:56
  • 1
    Then you have to populate it manually. WinForms `ListView` (and `TreeView`) controls do not support data binding :( – Ivan Stoev Jun 04 '16 at 11:56
  • What do you think about using the loop, which will add this data to ListView in some way? – nvent Jun 04 '16 at 12:04
  • Question with examples on how to fill a ListView with subitems http://stackoverflow.com/questions/729090/c-how-to-add-subitems-in-listview and of course MSDN https://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.listviewsubitem(v=vs.110).aspx – Steve Jun 04 '16 at 12:11
  • 1
    I found solution, thanks anyway. – nvent Jun 04 '16 at 13:08

1 Answers1

5

Ok, I found solution:

foreach (Book b in Program.ListBooks)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = b.IdBook.ToString();
                lvi.SubItems.Add(b.Author);
                lvi.SubItems.Add(b.Title);
                lvi.SubItems.Add(b.Year.ToString());
                listViewBooks.Items.Add(lvi);
            }
nvent
  • 81
  • 1
  • 8