Display specified text for list items
I have a list containing custom objects. These objects have different properties and I have ~ 100 of them. I want to create a list of them in the list, but the list shows only
MyNamespace.MyClass
MyNamespace.MyClass
MyNamespace.MyClass
MyNamespace.MyClass
...
Is it possible for the list to display a specific value for each item? Let's say my objects have an ID string value. Is it possible to display the ID for each item without discarding other properties of other objects?
I am currently populating the list this way:
lbox.Items.Clear();
lbox.Items.AddRange(list.ToArray());
source to share
Let's assume MyClass looks like this:
public class MyClass
{
public int Id { get; set; }
}
There are two options available.
-
You can use DataBinding for this.
Set
DisplayMember
to the setting of your MyClass which you want to displaylbox.DisplayMember = "Id";
Set elements using a property of
DataSource
yourListBox
lbox.DataSource = list.ToArray();
-
You can simply override the method of
ToString
your objectMyClass
and return the text you want to display.Override method of
ToString
your MyClasspublic class MyClass { public int Id { get; set; } public override string ToString() { return Id.ToString(); } }
Set the items the same way you mentioned
lbox.Items.AddRange(list.ToArray());
Additional Information
source to share