views:

39

answers:

1

After typing text into a combobox during run time, how do I add it to the combobox's items property? This is in C# 2010.

+1  A: 

The simple solution should be something like

Combobox.Items.Add(Combobox.Text);

A more elaborate solution would be perhaps to bind your Combobox.Items to some ObservableCollection in your ViewModel, and on some event (user presses Enter, etc.) the collection is updated by adding the new text (if it's still not there). This solution assumes WPF and MVVM-like approach.

Vlad
Thsnk you, but I tried this and it doesn't work.
robblot
What exactly doesn't work? Could you please check the following: (1) is your code called at all? (2) is the value of combobox.Text as expected? (3) is the value of Items collection after adding as expected?
Vlad
Here is my code:
robblot
private void cboDummy_SelectedTextChanged(object sender, EventArgs e) { cboDummy.Items.Add(cboDummy.Text); }
robblot
Okay. So please try to set a breakpoint there, in order to see whether it gets called at all. By the way, do you really need to update the list every time the user changes the text inside?
Vlad
Thank you for your time. Yes it does get called but only if I select something in the list. So it adds another of the same item in the list. There will only be a few entries, but I'm frustrated and I need to learn how to do this.
robblot
Well, what is your XAML definition of the combobox? You seem to subscribe to a wrong event.
Vlad