简体   繁体   中英

Adding new items to Combo Box when the user clicks on it

I have a Combo box which lists recipe names. The recipes are kept in a directory. When the user clicks on the combo, I need to add/delete items and display the new new drop down list. Which event can I use for updating the list

I would prefer following way. Add a ObservableCollection of your recipes to the class members:

ObservableCollection<Recipe> recipeList = new ObservableCollection<Recipe>();

Set the data source of your combo box and subscribe the Click EventHandler:

comboBox1.DataSource = recipeList;
comboBox1.Click += new EventHandler(comboBox1_Click);

In the click handler of the combobox you can add items to the list and "by magic" (due to the observable pattern) items will be shown in the combobox

void comboBox1_Click(object sender, EventArgs e)
{
    recipeList.Add(new Recipe { Name = "Spagetti Bolognese" });
}

您可以使用ComboBox选定索引已更改事件,但请确保在首次加载时具有默认值。

Double click the combo box in winform editor (or add an event handler for SelectedIndexChanged) and you should get something like

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    { 
    }

That will be fired everytime a user selects an item, then you can modify the items with comboBox1.Items.Add("test"); or something like that.

If you meant that everytime you click on the combo box the list is changed, you can take advantage of the Click event. Go to properties (of the combobox) and then events, and double click on Click. 例

That should generate code that will automatically fire whenever the component is clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM