在组合框中显示对象
本文关键字:显示 对象 组合 | 更新日期: 2023-09-27 18:01:27
我有这个方法,它接收一个对象的集合(EmployeeState(。这个对象包含以下属性:IdEmployeyState(int(、StateName(string(和Description(string(,我只需要在组合框中显示StateName。这就是方法。此查询linq的问题是显示所有列,如下所示:{StateName=Active}{StateName=NotActive}{StateName=已解除}
并且我只需要在组合框中显示名称:">活动"、">Not Active"answers">Dismissed。保持对象加载到组合框中(不要将其传递到字符串列表(
我该怎么做?
public void loadEmployeeStateCombobox(ICollection<EmployeeState> employeeStateCollection)
{
var result = from employeeState in employeeStateCollection
select new
{
//employeeState.StateName,
bb = employeeState.StateName
};
_employeeStatecomboBox.ItemsSource = result.ToList();
}
您可能还想使用Distinct来避免在组合中重复State:
_employeeStatecomboBox.ItemsSource =
employeeStateCollection.Select(e => e.StateName).Distinct();
WinForm中的ComboxBox要求具有DisplayMember和ValueMember。下面的代码向您展示了如何将值和显示设置为相同的值,但您也可以将值设置为状态的唯一标识符。
_employeeStatecomboBox.DataSource = employeeStateCollection.Select(e => e.StateName).Distinct();
_employeeStatecomboBox.DisplayMember = "StateName";
_employeeStatecomboBox.ValueMember = "StateName";
ASP.NET也存在同样的东西,但它来自我的记忆"DataTextField"answers"DataValueField"。
public void loadEmployeeStateCombobox(ICollection<EmployeeState> employeeStateCollection)
{
var result = from employeeState in employeeStateCollection
select new SelectListItem
{
//employeeState.StateName,
Value = employeeState.Id,//whatever the id prop is
Text=employeeState.StateName
};
_employeeStatecomboBox.ItemsSource = result.ToList();
}
或者创建一个字典,这也应该有效。