[英]Winform Combobox with DataSource as List<int>
This may be a very simple question but I realized I could not get it work. 这可能是一个非常简单的问题,但我意识到我无法使其正常运行。
I have a Winform combo box with datasource as a List<int>
我有一个Winform组合框,其数据源为
List<int>
combo.DataSource = intList;
What do I put for .DisplayMember
and .ValueMember
in order to simply have a list of integer values? 我应该为
.DisplayMember
和.ValueMember
放置什么,以便仅具有整数值列表? Not setting them will display nothing. 不设置它们将不显示任何内容。
I have worked with other List<myObj>
in which DisplayMember
and ValueMember
are myObj's properties. 我与其他
List<myObj>
一起工作,其中DisplayMember
和ValueMember
是myObj的属性。 How about simple data type like int
, string
? 简单的数据类型,例如
int
, string
呢?
When retrieving the selected item, one could simply cast (int)(combo.SelectedItem)
or have to go through the property corresponding to ValueMember
? 检索所选项目时,可以简单地
(int)(combo.SelectedItem)
或必须通过与ValueMember
对应的属性?
The problem does not occur because you have a list of integers, it probably occurs because you add items to the list after assigning it to the .DataSource
property. 不会发生此问题,因为您有一个整数列表,它可能是由于将项目分配给
.DataSource
属性之后将项目添加到列表中而.DataSource
。 List does not have a mechanism to notify its container when items are added to or removed from it. 列表没有机制来向其添加或删除项目时通知其容器。
Either add items to the list before assigning it to the .DataSource
property, or use a wrapper like BindingSource
as Krishnraj Rana suggested. 在将项目分配给
.DataSource
属性之前,将其添加到列表中,或者使用Krishnraj Rana建议的包装器(如BindingSource
。
Here BindingSource comes into picture. 在这里, BindingSource成为图片。 You can use it like this.
您可以像这样使用它。
BindingSource bSource = new BindingSource();
bSource.DataSource = new List<int> { 1, 2, 3 };
combo.DataSource = bSource;
Though you can set datasource of combobox directly with list. 虽然可以直接用列表设置组合框的数据源。 like this -
像这样 -
combo.DataSource = intList;
This also works perfectly fine. 这也很好用。
You can add items from list using foreach like this. 您可以像这样使用foreach从列表中添加项目。
foreach (var v in intList)
{
comboBox1.Items.Add(v.ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.