Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay, so I know how listboxes generally work with this example here.
C#
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.

C#
class Sailor
    {
        public int Number;

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

Then
C#
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;
        }

So now I'm ready to populate.
In Form1.cs I have this:
C#
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;
        }

I do not get any errors, but the only think that is displayed in the listbox is:
"SailingEvent.ProSailor"

What am I doing wrong?

What I want are those numbers in the brackets to be displayed in the listbox, but I also want words around them.

e.g: "Sailor " + number + ", " + age + "years of age has, " + noOfSailsFin + " races completed!"

Please give a guy a helping hand.

Cheers!
Posted

1 solution

Add an override method to your ProSailor class to handle ToString:
C#
public override string ToString()
    {
    return "Sailor " + Number + ", " + Age + "years of age has, " + NoOfSailsFin + " races completed!"
    }
 
Share this answer
 
Comments
fjdiewornncalwe 20-Aug-13 11:35am    
+5. Simple and effective.
JG92 20-Aug-13 11:53am    
Thanks mate! Saved me from hours of hair tearing! Cheers! :) +5!
OriginalGriff 20-Aug-13 12:25pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900