简体   繁体   English

如何在.NET ComboBox控件上获取选定的项目索引?

[英]How to get the selected item index on a .NET ComboBox control?

I have a ComboBox setup with 4 items, with indexes ranging from 0 to 3. 我有一个包含4个项目的ComboBox设置,索引的范围是0到3。

Later in my code, I need to do a certain event depending on what is selected. 在我的代码的后面,我需要根据选择的内容来做一个特定的事件。 To do this I thought about comparing what the index of the selected ComboBox item is, because integer comparison is faster than strings, right? 为此,我考虑过比较所选ComboBox项的索引是什么,因为整数比较比字符串快,是吗?

How can I get the index of the selected item? 如何获得所选项目的索引?

ComboBox has a SelectedIndex property. ComboBox具有SelectedIndex属性。

myComboBox.SelectedIndex

Regarding comparison: 关于比较:
If you're not doing millions of comparisons then this "optimization" wouldn't help you. 如果您不进行数百万次比较,那么这种“优化”将无济于事。

Are you sure that integer comparison is always faster than string comparison? 您确定整数比较总是比字符串比较快吗?

Depends how long the strings your comparing are... If you compare two strings that each only have one character then its a simple byte-wise AND operation which may be faster than comparing a 4 byte integer value. 取决于比较的字符串有多长...如果比较两个仅包含一个字符的字符串,则它是一个简单的按字节与运算,可能比比较4个字节的整数值要快。

Usually, you can get the list index of the current selected item using the ComboBox.SelectedIndex property. 通常,您可以使用ComboBox.SelectedIndex属性获取当前所选项目的列表索引。

However, I've come across situations where some text was typed into the combobox's text field, and the SelectedIndex property was not updated properly and contained the value -1 instead. 但是,我遇到了这样的情况:在组合框的文本字段中键入了一些文本,并且SelectedIndex属性没有正确更新,而是包含值-1 In such cases, you can use the ComboBox.FindStringExact method to find the list index of the entered text: 在这种情况下,可以使用ComboBox.FindStringExact方法查找输入文本的列表索引:

Dim selectedIndex As Integer = myComboBox.FindStringExact(myComboBox.Text)

(Btw., if no list item is found with the specified text, that function will return -1 .) (顺便说一句,如果找不到带有指定文本的列表项,则该函数将返回-1 。)

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

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