Some time ago I have encountered post in which the author stated that if I have a ListBox
the objects inside of it do not have to be represented by string
returned by ToString()
method inside of the ListBox
How is it possible?
For instance I have a:
public class Car {
public static int ID { get; set; }
public int Id { get; set; }
public string Make { get; set; }
public int Power { get; set; }
public Car(string Make, int Power) {
Id = ID++;
this.Make = Make;
this.Power = Power;
AddToClassExtension(this);
}
public override string ToString() {
return Id + "." + Make + " " + Power;
}
}
and a ListBox lb
in a Form
. I want to display only car.Id
in every row of the lb
but do not change ToString()
method. Is it possible?
You can specify the DisplayMember
for the ListBox
- in this case you'd set it to "Id"
so that the control would fetch that property from each item being displayed.
Here's a short but complete example (using C# 6 for brevity):
using System;
using System.Collections.Generic;
using System.Windows.Forms;
public class Car {
// C# 6 finally allows read-only autoprops. Yay!
public int Id { get; }
public string Make { get; set; }
public Car(int id, string make)
{
this.Id = id;
this.Make = make;
}
public override string ToString() {
return Id + "." + Make;
}
}
class Test
{
static void Main()
{
var cars = new List<Car>
{
new Car(10, "Ford"),
new Car(20, "Nissan"),
new Car(45, "Rolls-Royce")
};
var listBox = new ListBox
{
DataSource = cars,
DisplayMember = "Id",
Dock = DockStyle.Fill
};
var form = new Form
{
Controls = { listBox }
};
Application.Run(form);
}
}
For more complex formatting, you can use the Format
event, after enabling formatting. For example, in the above example, change the listBox
declaration to:
var listBox = new ListBox
{
DataSource = cars,
Dock = DockStyle.Fill,
FormattingEnabled = true,
};
listBox.Format += (sender, args) =>
{
var car = (Car) args.Value;
args.Value = string.Format("Id: {0}; Make: {1}", car.Id, car.Make);
};
See more on this question at Stackoverflow