问题
At my form, I have one control ComboBox. I want after databinding add text "Select". I try this
cbOperatorList.DataSource = operatorService.GetOperatorList();
cbOperatorList.Items.Insert(0, "Select");
But when I do this. I get exception what
Changing the collection of items is impossible if you set the property DataSource.
UPDATE
public BindingList<Operator> GetOperatorList(string filter = "")
{
return
new BindingList<Operator>(
this.operatorRepository.All.Where(
item => item.FirtsName.Contains(filter) || item.LastName.Contains(filter) || item.MiddleName.Contains(filter)).
ToList());
}
UPDATE
I fixed the problem, using this code
cbOperatorList.DataSource =
this.operatorService.GetOperatorList().Concat(new[] { new Operator { LastName = "Select", Id = 0 } }).OrderBy(
item => item.Id).ToList();
回答1:
If GetOperatorList() returns an immutable IEnumerable<T>, you can use linq to concatenate that with new object[] { "Select" }. Assuming that T is not object, you would have to cast:
cbOperatorList.DataSource = operatorService
.GetOperatorList()
.Cast<object>()
.Concat(new object[] { "Select" });
EDIT
If you want the word "Select" to appear at the beginning, reverse the concatenation:
cbOperatorList.DataSource = (new object[] { "Select" })
.Concat(
operatorService.GetOperatorList().Cast<object>()
);
回答2:
You don't describe what GetOperatorList() returns, but you could first set a variable to get that list and insert your item in the list before setting the DataSource to that variable.
You would have to refactor your code to handle this "Select" item to not get confused with your operator objects.
来源:https://stackoverflow.com/questions/8751701/winform-combobox-add-text-select-after-data-binding