Overriding ToString() and adding to ListBox C#

邮差的信 提交于 2020-01-02 02:34:51

问题


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());

回答1:


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...




回答2:


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";
    }
}



回答3:


Does it not have to be like this:

listBox1.Items.Add(test.ToString());

I assume you want your listbox to contain a string type?

Not sure if that is correct though, I haven't tested it.




回答4:


The items in a ListBox are a collection of objects, not strings.

See MSDN: ListBox.ObjectCollection.Add Method

Therefore you either have to add the the instance as a string (ex: listBox1.Items.Add(test.ToString());) on the front end or on the backend when looking at the listbox you have to call ToString (ex: listBox1.Items[0].ToString();).




回答5:


I came across this too (and another thanks there Manji!). I had something like this:

public override string ToString()
    {
        return  MessageText;
    }

Where MessageText was a text field amongst several others, and it worked fine. Later I changed it to this

public override string ToString()
    {
        return string.Concat("[", MessageTime.ToString("yyyy-MM-dd HH:mm:ss.fffff"), "] ", MessageText);
    }

And it would still return just MessageText field contents (hair pulling time). Interesting thing was that a context menu on the ListBox I had set up to copy selected items to the Clipboard, did use the full ToString override.

Personally I think the FormattingEnabled property should default to false rather than true, I find I often get caught out by the IDE (or control settings) trying to be smart.

///Edit: Typo (must remember not to type with elbows!



来源:https://stackoverflow.com/questions/5744105/overriding-tostring-and-adding-to-listbox-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!