Hello I'm trying to display items in a combobox but nothing appears. I used the property:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Items.Add("Item 1");
}
To add in an item but when I run my app the item doesn't 开发者_运维技巧show in the drop downlist.
I looked at a lot of MSDN articles but none have worked or perhaps I'm not getting it.
Is there something I'm missing with this?
If your ComboBox
is initially empty, then your SelectedIndexChanged
event is never getting fired because there is no selection to change. I would add the items to the ComboBox
somewhere else, perhaps in an Init()
function.
You might be misunderstanding how they work. Once you create the combobox and add it to some kind of UI container, the .NET Framework takes care of displaying it and showing the items it is initialized with when you click it. You don't need to manually handle making items show. Basically, what I'm getting at is if you make a combobox and add some items to it, then it will automatically show them whenever the control is clicked.
The SelectedIndexChanged
event is used typically used to make something happen when you select a different item from the CheckBox
then what it is currently showing.
You're adding an item (presumably the first) in the SelectedIndexChanged event. If there are no items in the combo box then the selected index can not change and the item will not get added.
The attached code will only add the item "Item 1" if you change the selected index of the combo box control. The selected index will only change if you click the combo box and select a new item. Thus, the item will never be displayed.
Try adding items at compile time (using the Items property in Visual studio with the combo box selected) or adding code to your OnLoad form event.
精彩评论