Reputation: 101
I'm reading in a field from a database into a list, like so
PaceCalculator pace = new PaceCalculator();
List<PaceCalculator> Distancelist = new List<PaceCalculator>();
while (Reader.Read()) //Loops through the database and adds the values in EventDistance to the list
{
pace.Distance = (int)Reader["EventDistance"];
Distancelist.Add(pace);
}
I want to put the values into a listbox, but when I do it like this:
listBox1.DataSource = Distancelist;
It only shows the class name, which is PaceCalculator
. It shows the right number of values, it just shows the class name instead. I want to see the integers in there.
Upvotes: 0
Views: 720
Reputation: 223402
You have two options,
ToString
in your class to return the required stringDistance
then specify that as DisplayMember
like:
listBox1.DisplayMember = "Distance";
listBox1.DataSource = Distancelist;
This will display you the Distance element from your list. Or you can override ToString
in your class PaceCalculator
like:
public override string ToString()
{
return string.Format("{0},{1},{2}", property1, property2, property3);
}
EDIT:
Based on your comment and looking at your code, You are doing one thing wrong.
this only displays the last value in the list, 46, 8 times
You are adding the same instance (pace
) of your class in your list on each iteration. Thus it is holding the last value (46)
. You need to instantiate a new object in the iteration like:
while (Reader.Read())
{
PaceCalculator pace = new PaceCalculator();
pace.Distance = (int)Reader["EventDistance"];
Distancelist.Add(pace);
}
Upvotes: 3
Reputation: 66509
Specify the property of PaceCalculator
to display.
listBox1.DataSource = Distancelist;
listBox1.DisplayMember = "Distance";
The ListBox
control allows you to pick a property from the collection to display to the user.
There's also a ValueMember
property that allows you to specify the value for each item in the ListBox
. Assuming your data included an id called "SomeUniqueRecordId", for instance:
listBox1.ValueMember = "SomeUniqueRecordId";
Upvotes: 1