'Load Listview C# with list of objects loop

I want to load information into a ListView from List of objects that I've created.

I've see info of how to do it without a loop( one by one) and i just want to do it dynamic and directly.

namespace Show
{
    public class Show
    {

        public string _bandName { get; set; }
        static int _counter = 1;
        public int _serialNum;
        public string _bandHit { get; set; }
        public  Festival _festival;

        
        public void setFestival(Festival y)
        {
            _festival = y;
            
        }

        public string printShow()
        {
            string str = "Name is: " + this._bandName + "Hit song is: " + this._bandHit + "";
            return str;

        }

        public Festival getFestival()
        {
            return _festival;
        }


        public virtual void playHit() { }

        public Show() {
        this._serialNum = _counter;
            _counter++;
        }

        public  Show(Festival z)
        {
            this._serialNum = _counter;
            _counter++;
            _festival = new Festival(z);


        }


        ~Show() { }

I have a list of object of Show class, i need it to preform in a list, something like that:

ID BandName band Hit
xx xxxxxx xxxxxxxx
xx xxxxx xxxxxxxx

Thank you for your help!



Solution 1:[1]

An option may be create your custom ListViewItem:

public class BandListViewItem : ListViewItem
{
    public BandListViewItem(Show show)
        : base(new[]
        {
            show._serialNum.ToString(),
            show._bandName,
            show._bandHit?.ToString()
        })
    {
        this.Show = show;
    }

    public Show Show { get; set; }
}

Using the base constructor in which you indicate the value of each column. Then, you can add items in this way:

var show = new Show();
this.listView1.Items.Add(new BandListViewItem(show));

var show1 = new Show();
var show2 = new Show();
this.listView1.Items.AddRange(new[]
{
    new BandListViewItem(show1),
    new BandListViewItem(show2)
});

And access to your Show:

var item = (BandListViewItem)this.listView1.Items[0];
var show = item.Show;

Don't forget setup your ListView:

this.listView1.View = View.Details;
this.listView1.Columns.Add("Id");
this.listView1.Columns.Add("Band Name");
this.listView1.Columns.Add("Band Hit");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor