Overriding ToString() and adding to ListBox C#

末鹿安然 提交于 2019-12-05 03:39:22
manji

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

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.

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

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!

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