从另一个类添加到列表框中,如何? [英] Adding to a listbox from another class, how?

查看:92
本文介绍了从另一个类添加到列表框中,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我知道列表框通常如何使用此示例。

Okay, so I know how listboxes generally work with this example here.

private void addList_Click(object sender, EventArgs e)
{
    List<string> myList = new List<string>

    myList.Add("one");
    myList.Add("two");
    myList.Add("three... You get the picture...");

    listBox1.DataSource = myList;
}



这一切都很好,而且很有效。但是,我有另一个我正在研究的程序,并且不能在我的生活中弄清楚我做错了什么。我正在尝试从多个类添加到列表框中。




That is all well and good and it works. However, I have another program that I am working on and cannot for the life of my figure out what I'm doing wrong. I'm trying to add to a listbox from multiple classes.

class Sailor
    {
        public int Number;

        public Sailor(int number)
        {
            this.Number = number;
        }
    }



然后


Then

class ProSailor : Sailor
    {
        public int Age { get; set; }
        public int NoOfSailsFin { get; set; } 

        public ProSailor(int number, int age, int noOfSailsFin) : base(number)
        {
            this.Age = age;
            this.NoOfSailsFin = noOfSailsFin;
        }



所以现在我已经准备好填充。

在Form1.cs中我有这个:


So now I'm ready to populate.
In Form1.cs I have this:

private void addList_Click(object sender, EventArgs e)
        {
            List<string> _scoreboard = new List<string>();
            ProSailor sailor1 = new ProSailor(1, 24, 7);
            ProSailor sailor2 = new ProSailor(2, 23, 14);
            ProSailor sailor3 = new ProSailor(3, 20, 5);

            _scoreboard.Add(sailor1.ToString());

            listBox2.DataSource = _scoreboard;
        }



我没有收到任何错误,但列表框中显示的唯一想法是:

SailingEvent。 ProSailor



我做错了什么?



我想要的是括号中的那些数字显示在列表框中,但我也想要它们周围的文字。



例如:水手+数字+,+年龄+年龄已经, + noOfSailsFin +比赛结束了!



请帮助一个人。



干杯!

推荐答案

为您的ProSailor类添加覆盖方法处理ToString:

Add an override method to your ProSailor class to handle ToString:
public override string ToString()
    {
    return "Sailor " + Number + ", " + Age + "years of age has, " + NoOfSailsFin + " races completed!"
    }


这篇关于从另一个类添加到列表框中,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆