WinForm ComboBox add text “Select” after data binding

余生长醉 提交于 2019-12-07 23:44:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!