简体   繁体   English

使用对象循环列表加载 Listview C#

[英]Load Listview C# with list of objects loop

I want to load information into a ListView from List of objects that I've created.我想从我创建的对象列表中将信息加载到 ListView 中。

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:我有一个 Show 类的对象列表,我需要它在列表中执行,如下所示:

ID ID BandName乐队名称 band Hit乐队命中
xx xx xxxxxx xxxxxx xxxxxxxx xxxxxxxx
xx xx xxxxx xxxxx xxxxxxxx xxxxxxxx

Thank you for your help!谢谢您的帮助!

An option may be create your custom ListViewItem :一个选项可能是创建您的自定义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 :并访问您的Show

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

Don't forget setup your ListView :不要忘记设置您的ListView

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM