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
2010-10-17 17:25:55
Thsnk you, but I tried this and it doesn't work.
robblot
2010-10-17 18:38:02
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
2010-10-17 18:47:19
Here is my code:
robblot
2010-10-17 19:26:28
private void cboDummy_SelectedTextChanged(object sender, EventArgs e) { cboDummy.Items.Add(cboDummy.Text); }
robblot
2010-10-17 19:26:56
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
2010-10-17 20:18:06
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
2010-10-17 22:48:04
Well, what is your XAML definition of the combobox? You seem to subscribe to a wrong event.
Vlad
2010-10-18 19:49:25