I am using Visual C# .NET 2003 to make a ComboBox accept
both mouse and keyboard selection. For mouse selection
code, I double-clicked ComboBox to get the
default "comboBox1_SelectedIndexChanged" event. This code
(see below) by itself works as expected with a mouse. But
when using keyboard arrows to navigate the ComboBox drop-
down, the SelectedIndexChanged event is triggered which
is what I don't want using the keyboard. Instead, I want
the selection to be made when user presses the "Enter"
key.
Also, to accept selection using ONLY keyboard, I coded
the "comboBox1_KeyDown" event. I want user to navigate
ComboBox drop-down list using arrow keys and on "Enter"
key, accept the selection. This code by itself works fine
(when "comboBox1_SelectedIndexChanged" event is commented
out). I am trying to make both of these events work
together but I am having a hard time figuring this out. I
tried playing with the "comboBox1_Click" event but that
didn't help. I also tried working with
the "SelectionChangeCommitted" event from a suggestion
but I'm still unsuccessful. Thanks in advance for any
help on this.
// Preliminaries...
this.comboBox1.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.Items.AddRange(new object[] {"Display form
A", "Display form B"});
this.comboBox1.KeyDown += new
System.Windows.Forms.KeyEventHandler
(this.comboBox1_KeyDown);
this.comboBox1.SelectedIndexChanged += new
System.EventHandler(this.comboBox1_SelectedIndexCh anged);
private void comboBox1_SelectedIndexChanged(object
sender, System.EventArgs e)
{
switch(comboBox1.SelectedItem.ToString())
{
case "Display form A":
MessageBox.Show("Display form A");
break;
case "Display form B":
MessageBox.Show("Display form B");
break;
}
}
private void comboBox1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
switch(comboBox1.SelectedItem.ToString())
{
case "Display form A":
MessageBox.Show("Display form A");
break;
case "Display form B":
MessageBox.Show("Display form B");
break;
}
}
}