开发者

Bind ComboBox to Two Lists in C#

I have two l开发者_如何学JAVAists. The first one is hard-coded and the contents never change. The second can be edited by the user to add, change and remove items:

public List<Item> DefaultItems = new List<Item>();
public BindingList<Item> UserItems = new BindingList<Item>();
...
MyTable.DataSource = UserItems;

I would like to bind the contents of both lists, one after the other, to a ComboBox and have it update automatically when the user edits the UserItems list.

The first part I can easily solve with something like:

public List<Items> AllItems
{
    get
    {
        List<Item> Items = new List<Item>();
        foreach (Item I in DefaultItems) Items.Add(I);
        foreach (Item I in UserItems) Items.Add(I);
        return Items;
    }
}
...
MyComboBox.DataSource = AllItems;

The problem is that when UserItems changes there is no notification that AllItems has changed so the contents of the combobox remain the same.

I then added an event that is generated when UserItems changes. Now my problem is how to force the ComboBox to refresh. Doing the following:

MyComboBox.DataSource = null;
MyComboBox.DataSource = AllItems;

results in the selecteditem becoming null and the selectedindex becoming -1, which I then have to handle in my code (temporarily remember the current item, restore it afterwards, etc.). It's all becoming very messy and I'm sure there is a clever way of solving this. Is there?

thanks, Andy

UPDATE: I didn't want to add yet more code and complexity just for this in the form of a third party assembly, so I just continued with my messy approach. Thanks.


You need to use a collection that will notify the UI when the collection has been changed.

You can either use the .NET provided BindingList class or, if you want to try something different, you could download the BindingListView class that will wrap your existing collections and provide the UI with the notification it needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜