Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding ToString() and adding to ListBox C#

Can anyone explain this:

public class Test : List<int>
{
    public override string ToString()
    {
        return "My ToString";
    }
}

If I instantiate this and add it to a ListBox control on a Windows Form, it displays "Collection" rather than "My ToString".

Test test = new Test();
listBox1.Items.Add(test);

I thought the add to Items would just call my class's ToString(). The following works as expected of course

MessageBox.Show(test.ToString());
like image 497
Ray Browning Avatar asked Apr 21 '11 12:04

Ray Browning


People also ask

What happen when you override a toString () method?

By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.

Why we do override toString ()?

Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

What happens if we don't override toString method?

toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.

What does toString () do in C #?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


2 Answers

For that to work you have to disable formatting:

listBox1.FormattingEnabled = false;

It looks like if formatting is enabled, its doing some magic tricks and the result is not always what it should be...

like image 190
manji Avatar answered Sep 23 '22 14:09

manji


Set the DisplayMember on the ListBox to the property of the Test type.

listBox1.DisplayMember = "Name";

To solve your problem, add a Property called "Name" to Type and in the getter call ToString.

public class Test : List<Int32>
{
    public String Name { get { return this.ToString(); } }

    public override string ToString()
    {
        return "Test";
    }
}
like image 38
Vijay Sirigiri Avatar answered Sep 21 '22 14:09

Vijay Sirigiri