我有这个方法,它接收一个对象的集合(EmployeeState)这个对象包含这个属性:IdEmployeeState(int),StateName(string)和Description(string),我需要在一个组合框中只显示StateName 。这是方法。此查询linq的问题是显示所有列,如下所示:{StateName = Active} {StateName = NotActive} {StateName = Dismissed}
我需要在Combobox中显示名称:“活跃”,“不活跃”和“已解雇”。保持对象加载到组合框中(不将其传递给字符串列表)
我该怎么做?
public void loadEmployeeStateCombobox(ICollection<EmployeeState> employeeStateCollection)
{
var result = from employeeState in employeeStateCollection
select new
{
//employeeState.StateName,
bb = employeeState.StateName
};
_employeeStatecomboBox.ItemsSource = result.ToList();
}
答案 0 :(得分:1)
您可能还想使用Distinct来不重复组合中的状态:
_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”和“DataValueField”。
答案 1 :(得分:0)
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();
}
或者创建一个也应该有效的词典。