[英]Values appear as the class name in the listbox
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
. 它仅显示类名称,即PaceCalculator
。 It shows the right number of values, it just shows the class name instead. 它显示正确数量的值,而仅显示类名。 I want to see the integers in there. 我想在那里查看整数。
You have two options, 您有两种选择,
ToString
in your class to return the required string 在您的类中重写ToString
以返回所需的字符串 Distance
then specify that as DisplayMember
或 ,如果只想显示Distance
则将其指定为DisplayMember
like: 喜欢:
listBox1.DisplayMember = "Distance";
listBox1.DataSource = Distancelist;
This will display you the Distance element from your list. 这将显示您列表中的Distance元素。 Or you can override ToString
in your class PaceCalculator
like: 或者,您可以在类PaceCalculator
重写ToString
,例如:
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 这只会显示列表中的最后一个值46次,共8次
You are adding the same instance ( pace
) of your class in your list on each iteration. 您将在每次迭代的列表中添加类的相同实例( pace
)。 Thus it is holding the last value (46)
. 因此,它保留了最后一个值(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);
}
Specify the property of PaceCalculator
to display. 指定要显示的PaceCalculator
的属性。
listBox1.DataSource = Distancelist;
listBox1.DisplayMember = "Distance";
The ListBox
control allows you to pick a property from the collection to display to the user. ListBox
控件使您可以从集合中选择一个属性以显示给用户。
There's also a ValueMember
property that allows you to specify the value for each item in the ListBox
. 还有一个ValueMember
属性,该属性使您可以为ListBox
每个项目指定值。 Assuming your data included an id called "SomeUniqueRecordId", for instance: 假设您的数据包含一个名为“ SomeUniqueRecordId”的ID,例如:
listBox1.ValueMember = "SomeUniqueRecordId";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.