简体   繁体   English

如何使用 windows 表单在 combobox 中显示项目?

[英]How to display items in combobox using windows form?

Hello I'm trying to display items in a combobox but nothing appears.您好,我正在尝试在 combobox 中显示项目,但没有出现任何内容。 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.我查看了很多 MSDN 文章,但没有一个有效,或者我没有得到它。

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.如果您的ComboBox最初是空的,那么您的SelectedIndexChanged事件将永远不会被触发,因为没有更改的选择。 I would add the items to the ComboBox somewhere else, perhaps in an Init() function.我会将这些项目添加到其他地方的ComboBox中,也许在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.创建 combobox 并将其添加到某种 UI 容器后,.NET 框架会负责显示它并在您单击它时显示它初始化的项目。 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.基本上,我要说的是,如果您制作 combobox 并向其中添加一些项目,那么只要单击控件,它就会自动显示它们。

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. SelectedIndexChanged事件通常用于在您 select 与CheckBox不同的项目时发生某些事情,然后是它当前显示的项目。

You're adding an item (presumably the first) in the SelectedIndexChanged event.您正在 SelectedIndexChanged 事件中添加一个项目(可能是第一个项目)。 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.如果您更改组合框控件的选定索引,附加的代码只会添加项目“项目 1”。 The selected index will only change if you click the combo box and select a new item.仅当您单击组合框和 select 新项目时,选定的索引才会更改。 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.尝试在编译时添加项目(使用 Visual Studio 中的 Items 属性并选择组合框)或将代码添加到 OnLoad 表单事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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