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());
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.
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.
toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.
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.
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...
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With