469,645 Members | 1,476 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,645 developers. It's quick & easy.

ComboBox Code for Mouse and Keyboard

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;
}
}
}
Nov 15 '05 #1
0 5186

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by ilPostino | last post: by
8 posts views Thread by Nolan Martin | last post: by
2 posts views Thread by pei_world | last post: by
9 posts views Thread by Strahimir Antoljak | last post: by
reply views Thread by Andrus | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.