Show an object in Combobox
I have this method, it receive an Collection of an object (EmployeeState) this object contains this properties: IdEmployeeState(int), StateName(string), and Description(string) , and I need show in a combobox ONLY the StateName. This is the method. The problem with this query linq is that show all the c开发者_开发百科olumn, like this: {StateName = Active} {StateName = NotActive} {StateName = Dismissed}
And I need show in Combobox only the name: "Active", "Not Active", and "Dismissed". keeping the object loaded into the combobox (NOT pass it to a list of string)
How can I do this?
public void loadEmployeeStateCombobox(ICollection<EmployeeState> employeeStateCollection)
{
var result = from employeeState in employeeStateCollection
select new
{
//employeeState.StateName,
bb = employeeState.StateName
};
_employeeStatecomboBox.ItemsSource = result.ToList();
}
You may also want to use Distinct to do not repeat the State in your combo :
_employeeStatecomboBox.ItemsSource =
employeeStateCollection.Select(e => e.StateName).Distinct();
ComboxBox in WinForm require to have DisplayMember and ValueMember. The code below show you how to set the value and the display with the same value but you can also set the value to the unique identifier of the state.
_employeeStatecomboBox.DataSource = employeeStateCollection.Select(e => e.StateName).Distinct();
_employeeStatecomboBox.DisplayMember = "StateName";
_employeeStatecomboBox.ValueMember = "StateName";
The same thing exist with ASP.NET but it's from my memory "DataTextField" and "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();
}
Or create a Dictionary, that should also work.
精彩评论