14
votes

After binding a list to combobox, its dataSource.Count is 5 but, combobox item count is 0. how can it be?

I'm used to Web programming and this is in Windows Forms. So no combo.DataBind(); method exists.

The problem here is, I'm trying to set the selected item programmatically. Since I don't see the combo.Items collection filled, I cannot set the desired item.


Update

A total update is needed I guess:

  • datasource contains 7 items
  • when bound to combobox, DisplayMember and ValueMember are appropriately implemented
  • after databound, through the gui, I can clearly see the 7 items in the combobox
  • combobox.DataSource.Count = 7 and combobox.Items.Count = 0

So the problem is here; since after databound no items are there in the ItemCollection of combobox; I cannot search for one to match and set the appropriate one.

Here is a image for better understanding (But I'm pretty sure I'm missing sth simple)

screenshot

3
Had you set the DataTextField and DataValueField accordingly?Andre Calil
Or DisplayMember and ValueMember. What datatype is in DataSource?Mr47
Yes, maybe the question is not fully understandable. The databound event is successfully working, I can see my items in the combo through the gui. The problem is, in debug; after the datasource assignment the combobox does not contain something in the Items collection. Like after the render, all of the items are shown but before that nothing there.Beytan Kurt
When you create a new BindingSource, all the bindings happen independantly of where that same datasource is utilized. Even if you've bound the datasource to 4 other controls, if each one has it's own BindingSource instance, they each have their own internal BindingContext that handles state/position/events relating to that particular control. You just solved it by explicitly telling the ComboBox to use a new BindingContext instead of letting the BindingSource take care of it.SPFiredrake
Crap, sorry, not an internal BindingContext, an internal CurrencyManager. Just took a look at the source. Either way, it should handle the events separately for each BindingSource that's used since it has it's own CurrencyManager (which again, handles state representation in the BindingSource itself for the specified DataSource, even if the DataSource is used elsewhere).SPFiredrake

3 Answers

24
votes

After adding ddl.BindingContext = new BindingContext(); before the BindingSource assignment, everything worked fine.

1
votes

If you'd expand DataSource items in debuger, you'd probably notice that 1st element on list is null. That is why DataSource does not render ComboBox Items. Removing null items from the list should do all the work;

0
votes

I had the same problem, but in my case it was caused by calling

combobox.Sorted = True

in InitializeComponent. I guess that call initializes Items, which then prevents the assignment to DataSource from updating it (Items).