Overriding ToString () and adding to a ListBox C #

Can someone explain this:

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

If I create this instance and add it to the ListBox control in Windows Form , it will display “Collection” and not “My ToString”.

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

I thought adding to Items would just call my ToString() class. Naturally, that

 MessageBox.Show(test.ToString()); 
+8
tostring generics c # winforms
source share
5 answers

To do this, you need to disable formatting:

 listBox1.FormattingEnabled = false; 

It seems that if formatting is turned on, it does some magic tricks, and the result is not always what it should be ...

+7
source share

Set DisplayMember in the ListBox to a property of type Test.

 listBox1.DisplayMember = "Name"; 

To solve your problem, add the "Name" property for Type to getter call ToString.

 public class Test : List<Int32> { public String Name { get { return this.ToString(); } } public override string ToString() { return "Test"; } } 
+4
source share

Shouldn't it be like this:

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

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

Not sure if this is true, but I have not tested it.

0
source share

Elements in a ListBox are a collection of objects, not strings.

See MSDN: ListBox.ObjectCollection.Add Method

Therefore, you need to add the instance as a string (ex: listBox1.Items.Add(test.ToString()); ) on the front or on the backend when viewing the list, which you should call ToString (ex: listBox1.Items[0].ToString(); ).

0
source share

I also stumbled upon this (and one more thanks to Manji!). I had something like this:

 public override string ToString() { return MessageText; } 

Where MessageText was a text box among several others, and it worked fine. I later changed it to

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

And it will still only return the contents of the MessageText field (hair extension time). Interestingly, the context menu in the ListBox that I configured to copy the selected items to the clipboard used the full ToString override.

Personally, I believe that the FormattingEnabled property should be false and not true, I believe that I often find that the IDE (or control settings) is trying to be smart.

/// Edit: Typo (do not forget to type elbows!

0
source share

All Articles