考虑有一个 ComboBox,它通过其 DataSource 属性填充。 ComboBox 中的每个项目都是自定义对象,ComboBox 设置有 DisplayMember
和 ValueMember
。
IList<CustomItem> aItems = new List<CustomItem>();
//CustomItem has Id and Value and is filled through its constructor
aItems.Add(1, "foo");
aItems.Add(2, "bar");
myComboBox.DataSource = aItems;
现在的问题是,我想将项目读取为将在 UI 中呈现的字符串。考虑到我不知道 ComboBox 中每个项目的类型(CustomItem
我不知道)
这可能吗?
最佳答案
绑定(bind):
ComboBox1.DataSource = aItems;
ComboBox1.DisplayMember = "Value";
获取项目:
CustomItem ci = ComboBox1.SelectedValue as CustomItem;
编辑:如果你想要得到的只是组合框所有显示值的列表
List<String> displayedValues = new List<String>();
foreach (CustomItem ci in comboBox1.Items)
displayedValues.Add(ci.Value);
关于c# - 获取已填充 DataSource 的 ComboBox 的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/867395/