获取 ComboBox 的当前索引? [英] Get the current index of a ComboBox?
问题描述
假设我有一个带有这些值的 ComboBox:
Say I had a ComboBox with these values:
Black
Red
Blue
而且我目前选择了 Red
.如果用户然后按退格键并按回车键,我将捕获 ComboBox 的 KeyDown
事件.
And I have Red
currently selected. If the user then hits backspace and hits enter I am capturing the KeyDown
event of the ComboBox.
在这种情况下,我想从组合框中的项目列表中删除红色.
In this event I want to delete Red from the list of items in the ComboBox.
但是,由于调用 KeyDown
时 ComboBox 的文本为空白,SelectedIndex
为 -1.
However, because the text of the ComboBox is blank by the time KeyDown
is called, the SelectedIndex
is -1.
目前我有一个看起来像这样的解决方法:
Currently I have a workaround that looks like this:
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
currentMyComboBoxIndex = myComboBox.FindStringExact(myComboBox.Text);
}
哪个有效..但我只是想知道是否有更好的方法.似乎这种方式可能会以某种方式中断,并且看起来有点混乱.有没有办法获取 ComboBox 的当前索引,而不必使用成员变量跟踪它并在索引更改时更新它?
Which works.. but I was just wondering if there is a better way. It seems like this way could break somehow and it seems a bit messy. Is there no way to get the current index of the ComboBox without having to keep track of it with a member variable and updating it when the index changes?
谢谢.
推荐答案
你的做法很好.您必须将所选索引保留在内存中,因为它在删除文本时返回 -1 作为 SelectedIndex.您也可以通过这种方式获取索引.
The way you are doing is fine. You have to keep the selected index in memory because it returns -1 as the SelectedIndex when the text is deleted. You could take the index in this way too.
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
currentMyComboBoxIndex = myComboBox.SelectedIndex;
}
这篇关于获取 ComboBox 的当前索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!