0

Is there any way to synchronize my List<string> with a ComboBox ?

What I'd like to have is my ComboBox, automaticly updating it's content depending on the List's changes.

I've tried using the ComboBox.DataSource property but this doesn't update the ComboBox, it only fills it once and that's all then, so ...

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
Jsncrdnl
  • 3,005
  • 5
  • 28
  • 43

3 Answers3

5

Use BindingSource object.

 List<string> list = new List<string>();
 BindingSource bsource=new BindingSource();

 //Set list dataSource
 bsource.DataSource = list;
 comboBox1.DataSource = bsource;

 //Now add an element via Binding object
 bsource.Add("One");
 bsource.Add("Two");

Or you may try ArrayList.Adapter method that creates Adapter wrapper of IList.

ArrayList items;

items=ArrayList.Adapter(comboBox1.Items);
items.Add("one");
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • It works using the `BindingSource` object! There's only one problem left : I instanciate many ComboBoxes using this List and all the ComboBoxes are synchronized together so ... – Jsncrdnl Feb 06 '12 at 09:24
2

Try replacing your List<string> with an ObservableCollection<string>.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Dominik
  • 3,342
  • 1
  • 17
  • 24
  • Do you use Databinding, if so use the ItemsSource property of the combobox – Dominik Feb 06 '12 at 08:28
  • The thing is that I'm probably using it the bad way... How do you set it as data resource for the ComboBox ? I tried with `.DataSource` it didn't work... And the type isn't accepted if I'm using `.DataBindings` so ... I just tried `ItemsSource`, the property doesn't exist... – Jsncrdnl Feb 06 '12 at 08:30
  • Ok, are we talking about WinForms or WPF? – Dominik Feb 06 '12 at 08:32
  • I'm using WinForms `System.Windows.Forms.ComboBox` – Jsncrdnl Feb 06 '12 at 08:33
  • AFAIK this does not work if you´re using WinForms, you have to call combobox.Refresh(); – Dominik Feb 06 '12 at 08:43
1

Please take a look at the sample: How to: Create and Bind to an ObservableCollection.

More information about binding sources: Binding Sources Overview.

Update:

Sorry, I have not mention that you're using Windows forms, so please see the question: WinForms ComboBox data binding gotcha.

Community
  • 1
  • 1