问题描述
说我有一个具有以下值的组合框:
Say I had a ComboBox with these values:
Black
Red
Blue
我目前选择了红色
。如果用户随后按下退格键并按下Enter键,则说明我正在捕获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.
我想从ComboBox的项目列表中删除Red。
In this event I want to delete Red from the list of items in the ComboBox.
但是,由于ComboBox的文本在 KeyDown 被调用,
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);
}
哪个工作..但我只是想知道是否有更好的方法。似乎这种方式可能会以某种方式中断,并且似乎有些混乱。
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?
谢谢。
/ p>
Thank you.
推荐答案
您的工作方式很好。您必须将选定的索引保留在内存中,因为删除文本后它会返回-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的当前索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!