首页 > 解决方案 > 如何为 VB.NET 中的组合框赋值?

问题描述

我有一个名为cbxType. 此组合框填充有:

cbxType.DataSource = [Enum].GetValues(GetType(Customer.CustomerType))

Customer.CustomerType枚举在哪里:

Public Enum CustomerType
    Retail
    SelfEmployed
    Company
End Enum

这可以很好地填充字段,但是如何在稍后的代码中将给定值分配给组合框?

我努力了:

cbxType.ValueMember = 0

但我得到:

System.ArgumentException: 'Cannot bind to the new display member.
Parameter name: newDisplayMember'

标签: vb.netcombobox

解决方案


当 ComboBox 绑定到一些简单实体的集合时,例如枚举 X..

  • 组合中显示的内容是返回的字符串X.ToString(),在这种情况下返回枚举文本名称,并且
  • 作为值返回的东西,显示的是组合,是 X。

因此,要更改组合显示的内容.SelectedValue,请将组合的设置为 X 类型的对象。在这种情况下,X 将是枚举成员之一:

cbxType.SelectedValue = CustomerType.SelfEmployed

ValueMember(及其伙伴DisplayMember)用于指示您希望组合用于显示和选定值的复杂对象的哪个属性。

例如,如果您已将您的组合绑定到 aList(Of Person)并且 Person 具有 FullName 和 Email 属性等,您可能会设置DisplayMember = "FullName"为使列表显示“John Smith, Jane Doe..”等,并且您可以设置 a ValueMember = "Email"so when John Smith 被选中,调用 SelectedValue 可能会返回“John.smith@example.com”

SelectedItem 将是整个 Person 对象。SelectedIndex 将是所选项目的数字索引,在组合显示的项目列表中,但请记住,在某些情况下,显示的列表可以按与基础集合不同的顺序排序


推荐阅读